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.

Syntax

mongodb.connect(path[, callback])

Parameters

  • •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 127.0.0.1
  • 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

Example

// 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");
   }
   else
      console.log("Error in the connectivity");
})

Output

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.

Updated on: 27-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements