Connecting MongoDB with NodeJS

Introduction to mongodb.connect

This method is used to connect the Mongo DB server with our Node application. This is an asynchronous method from MongoDB module.


mongodb.connect(path[, callback])


  • •path – The server path where the MongoDB server is actually running along with its port.

  • •callback – This function will give a callback if any error occurs.

Installing Mongo-DB

Before proceeding to try connect your application with Nodejs, we need to setup our MongoDB server first.

  • Use the following query to install mongoDB from npm.

npm install mongodb –save
  • Run the following command to set up your mongoDB on the specific localhost server. This will help in creating connection with the MongoDB.

mongod --dbpath=data --bind_ip
  • Create a MongodbConnect.js and copy-paste the following code snippet into that file.

  • Now, run the following command to run the code snippet.

node MongodbConnect.js


// Calling the required MongoDB module.
const MongoClient = require("mongodb");

// Server path
const url = 'mongodb://localhost:27017/';

// Name of the database
const dbname = "Employee";

MongoClient.connect(url, (err,client)=>{
   if(!err) {
      console.log("successful connection with the server");
      console.log("Error in the connectivity");


C:\Users\tutorialsPoint\> node MongodbConnect.js
(node:7016) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use `node --trace-deprecation ...` to show where the warning was created)
successful connection with the server.