Connect MongoDB database with Backend Application

In this quick tutorial, I'll walk you through the basics of how to get started using MongoDB with Node.js. We need to have some basic requirements ready which are as follows :-

Setup

First we need to have a MongoDB account. You can Create a free MongoDB Atlas cluster. Simply go to MongoDB site and register for a free account. (mongodb.com/cloud/atlas/signup)

Creating a Cluster

Next step is to create your cluster for your project but first we need to create a project. Head over to your Database account and create a new project. You can take the reference below on how to create a project.

sketchpad.pro_BFD4A1AD7AE85D25EE5.png After your project is ready you can now create a cluster we need to provide settings for security which is to give database access and network access.

Setting Database Access and Network Access

Head over to your project and click on Database access and provide the name and password and keep this password safe with you this is going to be used in our project and plays a important role as it will set you up as a admin. Click on add new database user.

Screenshot (19).png

After this give network access this is done for security reasons. Add your current IP address. Atlas only allows client connections to a cluster from entries in the project’s IP Access List. Each entry should either be a single IP address or a CIDR-notated range of addresses. So add your current IP address.

Screenshot (20).png Click on add IP address and add your current IP address under the Access List Entry.

Screenshot (21).png

If you have done all the above steps successfully now we are ready to create Cluster for our backend project. Head over to clusters under the data storage select Build a cluster and choose free tier plan.

Screenshot (22).png

We have three options to connect our backend with MongoDB. Which are as follows

  • Connect with the Mongo shell
  • Connect your application
  • Connect using MongoDB Compass

In this tutorial we are mainly focusing on how to connect using URL string.

Connecting your application through URL

For connecting your application we need to generate URL which will be used in our node.js project. Select the middle option which is Connect your application. This will lead you you to a page generating your URL through which you can connect your backend with the MongoDB database.

sketchpad.pro_F1EE89A726C039B59C0.png

Once your application is ready you can see the URL string and copy this URL . The URL string will look like this :-

mongodb+srv://manasisaiba:<password>@cluster0.x0wjq.mongodb.net/<dbname>?retryWrites=true&w=majority

Replace with the password for the manasisaiba user. Replace with the name of the database that connections will use by default. By default database is set as test Database.

sketchpad.pro_B8CCA36976067043FB0.png Now, You are all set to connect MongoDB database to your application.