Connecting With Mongo DB Using Mongoose In Node JS using Express Framework

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).

  1. 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.
    1. npm install body-parser  
    2. npm install express  
    3. npm install mongoose   
    4. npm install morgan  
    After you have finished Mongo installation, you can start Mongo DB to listen to your node application.
    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”.
    1. C:\Program Files\MongoDB\Server\3.2\bin  mongod --dbpath=c:\mongo   
    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.

  2. Coding up
    First, we will set up express, morgan, and body-parser. We will be using them later on.
    1. var express = require('express');  
    2. var logger = require('morgan');  
    3. var bodyParser = require('body-parser');  
    4. var app = express();  
    5. app.use(logger('dev'));  
    6. app.use(bodyParser.json());  
    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.
    1. var mongoose = require('mongoose');  
    2. mongoose.connect('mongodb://localhost:27017/mongotest');  
    Now, we will create a simple Todo schema with the fields Name and Content.
    1. var Schema = mongoose.Schema;  
    2.    
    3. // todos  
    4. var todosShema = new Schema({  
    5.     name: {  
    6.         type: String,  
    7.         required: true  
    8.     },  
    9.     content: {  
    10.         type: String  
    11.     }  
    12. });  
    13.    
    14. var Todos = mongoose.model('todos', todosShema);  
    We will add routes for fetching all todos.
    1. app.get('/todos', function(req, res) {  
    2.     Todos.find({}, function(err, todos) {  
    3.    
    4.         if (!todos) {  
    5.             res.statusCode = 404;  
    6.    
    7.             return res.json({  
    8.                 error: 'Not found'  
    9.             });  
    10.         };  
    11.    
    12.         if (!err) {  
    13.             return res.json({  
    14.                 status: 'OK',  
    15.                 todos: todos  
    16.             });  
    17.         } else {  
    18.             res.statusCode = 500;  
    19.             //  log.error('Internal error(%d): %s',res.statusCode,err.message);  
    20.    
    21.             return res.json({  
    22.                 error: 'Server error'  
    23.             });  
    24.         };  
    25.     });  
    26. });  
    Let's add route for fetching one todo by id.
    1. app.get('/todo/:id', function(req, res) {  
    2.     Todos.findOne({  
    3.         "id": req.param.id  
    4.     }, function(err, todos) {  
    5.    
    6.         if (!todos) {  
    7.             res.statusCode = 404;  
    8.             return res.json({  
    9.                 error: 'Not found'  
    10.             });  
    11.         };  
    12.    
    13.         if (!err) {  
    14.             return res.json({  
    15.                 status: 'OK',  
    16.                 todos: todos  
    17.             });  
    18.         } else {  
    19.             res.statusCode = 500;  
    20.             //  log.error('Internal error(%d): %s',res.statusCode,err.message);  
    21.    
    22.             return res.json({  
    23.                 error: 'Server error'  
    24.             });  
    25.         };  
    26.     });  
    27. });  
    1. app.post('/todo', function(req, res) {  
    2.    
    3.     var tdos = new Todos({  
    4.         name: req.body.name,  
    5.         content: req.body.content  
    6.     });  
    7.    
    8.     tdos.save(function(err, todos) {  
    9.         console.log(err);  
    10.         if (!err) {  
    11.             return res.json({  
    12.                 status: 'OK',  
    13.                 todos: todos  
    14.             });  
    15.         } else {  
    16.             res.statusCode = 500;  
    17.             res.json({  
    18.                 error: 'Server error'  
    19.             });  
    20.         }  
    21.     });  
    22. });  
    1. app.put('/todo/:id', function(req, res) {  
    2.    
    3.     var tdos = {  
    4.         name: req.body.name,  
    5.         content: req.body.content  
    6.     };  
    7.    
    8.     Todos.findOneAndUpdate({  
    9.         "id": req.param.id  
    10.     },tdos,function(err, todos) {  
    11.         console.log(err);  
    12.         if (!err) {  
    13.             return res.json({  
    14.                 status: 'OK',  
    15.                 todos: todos  
    16.             });  
    17.         } else {  
    18.             res.statusCode = 500;  
    19.             res.json({  
    20.                 error: 'Server error'  
    21.             });  
    22.         }  
    23.     });  
    24. });  
    1. app.delete('/todo/:id', function(req, res) {  
    2.    
    3.     Todos.findOneAndRemove({  
    4.         id: req.param.id  
    5.     },function(err, todos) {  
    6.         console.log(err);  
    7.         if (!err) {  
    8.             return res.json({  
    9.                 status: 'OK',  
    10.                 todos: todos  
    11.             });  
    12.         } else {  
    13.             res.statusCode = 500;  
    14.             res.json({  
    15.                 error: 'Server error'  
    16.             });  
    17.         }  
    18.     });  
    19. });  
    Finishing up.
    1. // If no route is matched by now, it must be a 404  
    2. app.use(function(req, res, next) {  
    3.     var err = new Error('Not Found');  
    4.     err.status = 404;  
    5.     next(err);  
    6. });  
    7.    
    8. // Start the server  
    9. app.set('port', 3000);  
    10.    
    11. var server = app.listen(app.get('port'), function() {  
    12.     console.log('Express server listening on port ' + server.address().port);  
    13. });  
  3. 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. 

  4. Start your node server from command prompt using this command.
    1. node server.js  
    Getting all todos.



    Getting one todo.



    Saving/ storing todo.


     Updating/ changing todo

     

    Deleting/ removing todo


Ebook Download
View all
Learn
View all