Nodejs connect with MongoDB

To connect with MongoDB, Firstly we have to install the MongoDB module in the Nodejs


npm install mongodb --save

Now, create a server.js file and put the below code


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

let url="mongodb://localhost:27017/databaseName";
// Connect to the db
MongoClient.connect(url, function (err, db) {
   
     if(err) throw err;

     console.log("Database connected");
                
});

Now check database is connected or not


node server.js

If connected then show message “Database connected” otherwise not.