1. Overview

In this article, we will look into database connection with MongoDB along with JSON web service by using an example. Nowadays, most of the developers focus on fast and reliable implementation methodology.  MongoDB is a NoSQL database so it is recommended when data is straight forward.

1.1 MongoDB

It is an open-source NoSQL database. In NodeJS we need MongoClient for connecting MongoDB with our application. Mongodb is easy to use, so we there will be no need to create table as we do in relational databases due to the above reasons, Mongodb is very popular.

1.2 REST Api

It’s a standard for select, insert, update and delete records. Rest is a standard which is followed by the developer while implementing their web services.

REST gives a basic idea about how to deal with CRUD operation on a specific entity or table. It also provides information regarding the URL pattern for performing CRUD operations. You can read more about rest API in our previous article regarding nodejs json web service example.

1.3 Postman

It’s software for testing the REST api. By using this software, we can configure request and it’s parameters like cookies, headers etc.

2. Example for REST Api with mongodb

Let’s start with the basic database connection. For this, you need to install MongoDB database in your computer.

2.1 File Structure

Folder structure for mongodb nodejs integration

2.1.1 Folder structure for mongodb nodejs integration

2.2 Installing Dependencies

First of all, let’s start with understanding the use of full dependencies and installing all the required dependencies by given command.

  1. Mongodb is a native driver for nodejs which interacts with mongodb  instance.
    • npm i mongodb
  2. Express is a nodejs framework that provides features like allow HTTP utilities methos and middleware for creating restApi.
    • npm i express
  3. Body-parser as name indicates it parses request body.
    • npm i body-parser

2.3 Example

Here you can see the basic setup for all the dependency and application.

const express = require('express');
const bodyParser = require('body-parser');
const mongoClient = require('mongodb');
const app = express();


const dbUrl = 'mongodb://localhost:27017'

let dbo = undefined;
mongoClient.connect(dbUrl, (err, client) => {
    console.log('connected.....');
    db = client.db("Employee");
    require('./routes')(app, db) //import routes
});

// Collections are similar to tables in relational db
console.log('collection is created.....!!!!!');


// parse application/json
app.use(bodyParser.json());
app.listen(3000);
console.log('Application started.....~!!!!!')

In above code we are connecting our application with mongodb using mongoClient.connect() method. it will take database url as a first argument and return callback. Here we passed Employee as a database name if that database is not present then it will automatically create new database.

Now let’s add routes for CRUD operations. In our case, we specified all the routes in file named Routes.js and imported that in index.js. It’s a good approach for code separation.

//routes.js
module.exports = (app, db) => {
    app.get('/employee/:id', (req, res) => { // get employee by id 
        db.collection('employee').find({}).toArray(function(err, result) {
            console.log('Employee With Id '+req.params.id + ' Is Requested')
            return res.send(result);
        });
    });
    
    app.get('/employee', (req, res) => { // get all employee 
        const data = db.collection('employee').find({})
        let emp = [];
        data.each((err, item) => {
            if(item == null) {
                // here we can close connection
                console.log('Requested for all the employee');
                return res.send(emp);
            }
            emp.push(item);
        });
    });
    
    app.delete('/employee/:id', (req, res) => { //delete employee by id 
        console.log('Employee With Id '+req.params.id + ' Is Deleted')
        db.collection("employee").deleteOne({"id": req.params.id}, (err, data) => {
            console.log('Employee deleted.....!!!!');
            if(!err)
                return res.send("Employee deleted");;
        });
    })
    
    app.delete('/employee', (req, res) => { //delete all employee 
        db.collection("employee").deleteMany({}, (err, data) => {
            console.log('All Employees deleted')
            return res.send("All Employees Deleted")
        })
    })
    
    app.post('/employee', (req, res) => { //add new employee
        console.log(req.body);
        db.collection('employee').insertOne(req.body, (err, data) => {
            if(err)
                return res.send('Error while insert data');
            console.log('Employee Added');
        })
        res.send("New Employee Added")
    })

    app.put('/employee/:id', (req, res) => { //update particular employee 
        var query = { id: req.params.id };
        var newvalues = { $set: {name: req.body.name} };
        db.collection("employee").updateOne(query, newvalues, (err, data) => {
            return res.send("Employee Updated");
        })
    })
};

We are importing routes.js in index.js by passing database connection object. Which makes our application straight forward and easy to maintain. Other way is that instead of passing db connection, we can store dbConnection object in global variable.

2.4 Output

By using postman you can see the output for example. For getting all the employees postman lookalike this.

postman get all employee

2.4.1 postman get all employee

3. Conclusion

In this article, we learned about how to connect MongoDB with Nodejs application. How to handle database object effectively.

4. Reference

Was this post helpful?

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *