Node.js Connect to MongoDB

Node.js Connect to MongoDB – In this Node.js Tutorial, we shall learn to connect to MongoDB from Node.js Application.

The prerequisite to connect to a MongoDB, is having MongoDB installed in the computer. If you have not installed MongoDB yet, refer this tutorial – Install MongoDB.

Steps to Connect to MongoDB via Node.js

To connect to MongoDB from Node.js Application, following is a step by step guide.

Step 1: Start MongoDB service.

Run the following command to start MongoDB Service.

sudo service mongod start

Step 2: Install mongodb package using npm (if not installed already).

arjun@nodejs:~/workspace/nodejs/mongodb$ npm install mongodb
npm WARN saveError ENOENT: no such file or directory, open '/home/arjun/workspace/nodejs/package.json'
npm WARN enoent ENOENT: no such file or directory, open '/home/arjun/workspace/nodejs/package.json'
npm WARN nodejs No description
npm WARN nodejs No repository field.
npm WARN nodejs No README data
npm WARN nodejs No license field.

+ mongodb@2.2.33
added 9 packages in 9.416s

Step 3: Prepare the url.

A simple hack to know the base url of MongoDB Service is to Open a Terminal and run Mongo Shell.

arjun@nodejs:~$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://
MongoDB server version: 3.4.9
Server has startup warnings: 
2017-10-29T18:15:36.110+0530 I STORAGE  [initandlisten]

While the Mongo Shell starts up, it echoes back the base url of MongoDB.


Step 4: With the help of mongodb package, create a MongoClient and connect to the url.


Example 1 – Connect to MongoDB via Node.js

Following is an Example Node.js program to make a Node.js MongoDB Connection.


// URL at which MongoDB service is running
var url = "mongodb://localhost:27017";

// A Client to MongoDB
var MongoClient = require('mongodb').MongoClient;

// Make a connection to MongoDB Service
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Connected to MongoDB!");


arjun@java:~/workspace/nodejs/mongodb$ node node-js-mongodb-connection.js 
Connected to MongoDB!


In this Node.js MongoDB – Node.js Connect to MongoDB, we have learnt to find the url of the MongoDB Service and connect to the service from Node.js using MongoClient’s connect method, demonstrated by an Example program.