JavaScript

How to connect Node.js server to MongoDB database in MERN Stack Development

If you want to develop an application based on MERN Stack that saves any form of the data such as events, comments, user profiles, content, and uploads, you will need a simple database to use with the front-end and back-end. This is the situation where MongoDB comes into play. In the React.js front end, the created JSON documents are sent to the Express.js and the Node.js server, processing them and storing them in the MongoDB database.

This write-up will demonstrate how to create a MongoDB account and generate the connection string for your Project cluster. Moreover, the procedure of connecting the Node.js server to the MongoDB database in MERN Stack development will be also provided. So, let’s start!

Note: Before connecting the Node.js server to the MongoDB database, ensure that you have set up the Node server and it is running on the specified port.

How to create MongoDB database in MERN Stack Development

When we think about databases, rows, tables, and other relational concepts come to our minds. MongoDB offers similar principles, although they are referred to differently. For instance, in MongoDB, we have “Collections” instead of tables, “Documents” instead of rows. For storage purposes, MongoDB uses the Binary JSON (BSON) format, and it also offers a wide range of data types supported by the JSON, such as ISODates, Decimal128.

In MERN stack development, having a MongoDB database account is necessary. Creating a MongoDB account permits you to build a database according to your requirements. After that, you can add a “Cluster” to the newly created database and generate a connection string, which will assist you in connecting the Node.js server to the MongoDB database. So, let’s start this procedure by moving towards the official website of MongoDB:

Now, create an account for hosting the database in the “MongoDB Atlas”:

You will see the below-given dashboard after MongoDB account creation. Now, click on the “New Project” button, which is located at the right side of the dashboard:

In the highlighted input field, enter your MongoDB project name and click on the “Next” button:

At this point, your MongoDB project is created, and you are all ready to build a new database:

Next, select the provider and the zone for your database. For instance, we have selected “Google Cloud” as a cloud provider and “lowa” as our region. It is also recommended to choose a free tier that is great for a sandbox environment.

After selecting the required options, click on the “Create Cluster” button to move ahead:

To maintain the MongoDB security, choose an option between “Username and Password” and “Certificate” for authenticating the connection from or to the Node.js. In our case, we have added the username and password:

Now, add your IP addresses to the MongoDB safelist. This option will permit the configured IP address to access the project’s clusters:

After setting up the IP address, click on the “Finish and Close” button:

Within a few minutes, the created cluster of your MongoDB project will be provisioned:

How to generate a MongoDB string to connect Node.js server in MERN Stack Development

After setting up “Employee-mern-project” database and the newly created “Cluster0”, go to the “Database Deployments” section and select the cluster. After doing so, click on the “Connect” button, which is highlighted in the below-given image:

Then, you will be asked to choose the connection method for Cluster0. We want to connect our Node.js server to the MongoDB database in MERN Stack application development, so we will go with the “Connect your application” options:

Next, select the “DRIVER” and its “VERSION” and then copy the connection string from the bottom of the window:

How to connect Node.js server to MongoDB database in MERN Stack Development

In MERN Stack development, to connect the Node.js and the MongoDB database, we will use the connection string, which we have copied in from the “Connect to Cluster0” window. To do so, open up Node.js “server.js” file and make sure your server is running:

> nodeman server

In the next step, we will add the “mongoose” library. The “mongoose” Node.js library helps in establishing a connection between the MongoDB cluster and Node.js server:

const mongoose = require('mongoose');

Now, we will create a separate “.env” file for storing the MongoDB Atlas “URI” or the “Connection String”. For this purpose, click on the Node.js server folder, which is “backend” in our case, and then create a “New File”:

We have named the newly created file as “.env”:

If you do not have the connection string, then copy it from the highlighted section:

Then, add the copied connection string as “ATLAS_URI” in the “.env” file:

ATLAS_URI=mongodb+srv://linuxhint:@cluster0.8jdc7.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

In the added “ATLAS_URI,” specify your MongoDB username and password and press “CTRL+S” to save the added changes:

Now, add the following code in your Node.js “server” file:

const uri = process.env.ATLAS_URI;
mongoose.connect(uri);
const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})

The added code will connect with the “MongoDB Atlas” using the “mongoose” library and the ALTAS_URI. If the connection gets established, it will print out “MongoDB database connection established successfully” on the terminal window:

Press “CTRL+S” to save the added changes and then run your Node.js server:

> nodemon server

The below-given output declares that we have successfully connected our Node.js server to the MongoDB database in the MERN Stack development:

Conclusion

In MERN Stack development, “MongoDB” is used to store the data received from the application front end and then processed by the Node.js server. For creating a connection between your Node.js server and the MongoDB database, you will need a connection string generated by the created project cluster. This write-up showed you how to create a MongoDB account and generate the connection string for your Project cluster. Moreover, the procedure of connecting the Node.js server to the MongoDB database in MERN Stack development is also provided.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.