We are going to make web APIs using Express.js and will connect them to Mongo database. As you are aware, Mongo DB is a no-SQL type database and nowadays used very popularly. There are a lot of companies building services on top of it.
We will be creating a simple to-do web API in Express.js, so we will be supporting basic adding, retrieving, updating and deleting to-dos. We will be testing our web API using Postman.
This entire tutorial is available on github link here
Software needed
- Node JS - Platform
- Mongo DB- database provider
- Postman – used for creating HTTP requests like GET, PUT, POST, DELETE
- Sublime/Notepad++ - IDE for writing code.
Before getting started, you have to install the software mentioned above according to your platform ( Win/ Mac/ Lin).
- Installing dependencies
You need to install the following packages in your node.js project. Mongoose will help in connecting and executing queries on Mongo DB. Morgan will help you log every event to the console so that we can check for the error.
After you have finished Mongo installation, you can start Mongo DB to listen to your node application.- npm install body-parser
- npm install express
- npm install mongoose
- npm install morgan
Go to command prompt and then change the current directory to MongoDB\Server\3.2\bin where you will find mongod.exe. For Windows, it will be inside “program files”.
You need to mention file path after dbpath where you want to mongo to store db files. As soon as you run last query, your server will start listening to external ports.- C:\Program Files\MongoDB\Server\3.2\bin mongod --dbpath=c:\mongo
-
Coding up
First, we will set up express, morgan, and body-parser. We will be using them later on.
We need to connect to Mongo DB and the below statement will connect your application to Mongo where mongotest is the database name. Do not worry, if the mentioned database does not exist, it will automatically create for you.- var express = require('express');
- var logger = require('morgan');
- var bodyParser = require('body-parser');
- var app = express();
- app.use(logger('dev'));
- app.use(bodyParser.json());
Now, we will create a simple Todo schema with the fields Name and Content.- var mongoose = require('mongoose');
- mongoose.connect('mongodb://localhost:27017/mongotest');
We will add routes for fetching all todos.- var Schema = mongoose.Schema;
- // todos
- var todosShema = new Schema({
- name: {
- type: String,
- required: true
- },
- content: {
- type: String
- }
- });
- var Todos = mongoose.model('todos', todosShema);
Let's add route for fetching one todo by id.- app.get('/todos', function(req, res) {
- Todos.find({}, function(err, todos) {
- if (!todos) {
- res.statusCode = 404;
- return res.json({
- error: 'Not found'
- });
- };
- if (!err) {
- return res.json({
- status: 'OK',
- todos: todos
- });
- } else {
- res.statusCode = 500;
- // log.error('Internal error(%d): %s',res.statusCode,err.message);
- return res.json({
- error: 'Server error'
- });
- };
- });
- });
- app.get('/todo/:id', function(req, res) {
- Todos.findOne({
- "id": req.param.id
- }, function(err, todos) {
- if (!todos) {
- res.statusCode = 404;
- return res.json({
- error: 'Not found'
- });
- };
- if (!err) {
- return res.json({
- status: 'OK',
- todos: todos
- });
- } else {
- res.statusCode = 500;
- // log.error('Internal error(%d): %s',res.statusCode,err.message);
- return res.json({
- error: 'Server error'
- });
- };
- });
- });
- app.post('/todo', function(req, res) {
- var tdos = new Todos({
- name: req.body.name,
- content: req.body.content
- });
- tdos.save(function(err, todos) {
- console.log(err);
- if (!err) {
- return res.json({
- status: 'OK',
- todos: todos
- });
- } else {
- res.statusCode = 500;
- res.json({
- error: 'Server error'
- });
- }
- });
- });
- app.put('/todo/:id', function(req, res) {
- var tdos = {
- name: req.body.name,
- content: req.body.content
- };
- Todos.findOneAndUpdate({
- "id": req.param.id
- },tdos,function(err, todos) {
- console.log(err);
- if (!err) {
- return res.json({
- status: 'OK',
- todos: todos
- });
- } else {
- res.statusCode = 500;
- res.json({
- error: 'Server error'
- });
- }
- });
- });
Finishing up.- app.delete('/todo/:id', function(req, res) {
- Todos.findOneAndRemove({
- id: req.param.id
- },function(err, todos) {
- console.log(err);
- if (!err) {
- return res.json({
- status: 'OK',
- todos: todos
- });
- } else {
- res.statusCode = 500;
- res.json({
- error: 'Server error'
- });
- }
- });
- });
- // If no route is matched by now, it must be a 404
- app.use(function(req, res, next) {
- var err = new Error('Not Found');
- err.status = 404;
- next(err);
- });
- // Start the server
- app.set('port', 3000);
- var server = app.listen(app.get('port'), function() {
- console.log('Express server listening on port ' + server.address().port);
- });
-
Testing your API
We will be testing our API using postman with some sample data. You need to make sure your Mongo DB is listening to your requests. We will be testing for getting, storing, updating, and deleting todos. - Start your node server from command prompt using this command.
-
Getting all todos.
- node server.js

Getting one todo.

Saving/ storing todo.

Updating/ changing todo
Deleting/ removing todo

Join the conversation! Your thoughts help the community grow.