TechAE Blogs - Explore now for new leading-edge technologies

TechAE Blogs - a global platform designed to promote the latest technologies like artificial intelligence, big data analytics, and blockchain.

Full width home advertisement

Post Page Advertisement [Top]

How To Connect Node JS With Mongo DB


In the previous series, we created our first node application, now let's suppose we have to connect our Node JS Application with MongoDB. Now, here I am providing some steps to easily integrate MongoDB into your app. If you want to learn more about MongoDB and how to set it up easily, you can check out this link.

Table of Contents

  • Node JS is Installed, you can follow from here too
  • Installing MongoDB
  • Updating index.js
  • Executing node application

How to connect Node JS with MongoDB?

After completing reading documentation mongodb node js driver, I was able to specifically use these steps to rapidly set up my project.

Step 1: Setting up the Node project

You can create your brand new node project from scratch using this tutorial:

How To Create Your First Node JS Application

Step 2: Installing MongoDB

You can setup MongoDB local cluster using this tutorial:

Diving Into The World Of NOSQL Databases With MongoDB. 

After that, you can install this npm package to add the MongoDB module to your project.


> npm i mongodb

Step 3: Updating index.js

Now, you can write the below code to connect the node js driver with MongoDB. You have to edit the hostname and port number in the below connection URI.


const mongodb = require("mongodb");
const MongoClient = require("mongodb").MongoClient;

/**
 * Connect Mongo Driver to MongoDB.
 */
let db;
MongoClient.connect("mongodb://hostname:port", (err, client) => {
  if (err) {
    console.log(
      "MongoDB Connection Error. Please make sure that MongoDB is running."
    );
    process.exit(1);
  }
  db = client.db("database_name");
});

Add your database name in place of "database_name".

Step 4: Executing node application

Now, let us check if our MongoDB is connected and returning the response, so I am gonna write a get method to find all collections in our database. Replace "collection_name" with your collection name.


app.get("/", (req, res) => {
  db.collection("collection_name")
    .find({})
    .toArray(function (err, result) {
      if (err) throw err;
      console.log(result);
    });
});

Run your node js app by running this command:


> nodemon index.js

Finally, you can see that your results will be displayed in your terminal.

Now, you guys know how to set up MongoDB with your Node JS application all by yourself.

If you wish to check out more articles on the market’s most trending technologies like Big Data, Python, and Computer Vision, then you can refer here.

I will be releasing an article on how to add Redis with your MongoDB database and more.

See you next time,
@TechAE

No comments:

Post a Comment

Bottom Ad [Post Page]