Node Js - Connect node app with the MongoDB database

Node Js - Connect node app with the MongoDB database


Download MongoDB driver for node JS using the npm package

npm install mongodb

Note: Make sure that MongoDB is installed and MongoDB server is running in the background to make a connection of node app to the MongoDB database.

To run MongoDB server in the background, Open a cmd with admin and run

"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --dbpath="c:\data\db"


const mongodb = require("mongodb");

const MongoClient = mongodb.MongoClient;

const connectionURL = "mongodb://localhost:27017";

const dbName = "demoProject";

MongoClient.connect(connectionURL, (error, client) => {
  if (error) {
    return console.log(error);
  }

  const db = client.db(dbName);

  db.collection("products").insertOne({
    title: "A book",
    desc: "A great book to read",
  });

console.log('Record created')
client.close();
});



Open the MongoDB Compass GUI tools to view the created collection in the database










Post a Comment

0 Comments