NodeJs – Connect With MongoDb

In this chapter, we gonna see how to get connect MongoDb database with Nodejs Application.
MongoDb is one of most popular NoSql database.

You can download a free MongoDB database at

After installation,You need to start a mongod for handles the request, manages data access and perform the background management operation. you need to create a folder for Mongod operation .I have created that local folder in the name mongofolder in D: drive . Let start Mongod with below code in your Cmd Prompt.

C:\Program Files\MongoDB 2.6 Standard\bin>mongod.exe --dbpath "d:mongofolder"

Installing MongoDb:

we need to install Mongodb driver using NPM for get connected with MongoDB database.Run the below code in your Cmd Prompt .

npm install mongodb --save

Connecting MongoDB:

The following code tell how the MongoDb is connected with Nodejs.

var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
     if(err) throw err;
      console.log("Successfully connected with MongoDb")	
     //Write database Insert/Update/Query code here..              

save the above code in a file mongoconn.js in your project folder .run the file and see the results .

d:nodeproject>node mongoconn.js 
Successfully connected with MongoDb

Next chapter -> Express Framework

Leave a Reply

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