Connect MongoDB Atlas with Express Backend

Choosing the right database for an application is really important. If the backend is built with Node.js or Express, then the most suitable database is MongoDB. Storing the entire DB in our local server is most risky. It’s better to use a cloud database. Here in this article, we will discuss the steps to connect an Express backend with the MongoDB Atlas database.

Prerequisites

I assume that the reader has basic knowledge in Node.js, Express.js and MongoDB. We will create a simple express backend and use Postman tool for verifying the APIs we have made.

What we will learn

After completing this tutorial, we will learn:-

  • Create a MongoDB Atlas cloud database
  • To create an Express backend and APIs
  • Connect the Express backend with the database created
  • Verify the APIs created in the backend using the Postman tool.

Create MongoDB Atlas cloud database

At first, we are going to create a cloud database on MongoDB Atlas. It providers the easiest way to deploy, operate and scale MongoDB in the Cloud.

Let us discuss it in step by step with screen shots and explanations.

1. Create an account on MongoDB Atlas

We need a MongoDB account for creating a database. So, log on to the MongoDB page and Sign Up for an account. Or we can simply create an account and log in using our Google account.

2. Setup our MongoDB account

After creating an account, we will see a page to enter our organization and project details. We will also get an option to choose our preferred programming language. Because we are using Node/ Express.js backend, we can choose JavaScript in this category.

3. Create a cluster

The word cluster may confuse you. It is actually a server where MongoDB stores our data. Choosing the right plan before creating a cluster is important. Let us discuss about the plans first.

  • Dedicated Multi-Cloud & Multi-Region Cluster – If we are developing a project for global users, then choosing this plan is great. Because it stores the data in dedicated servers located in multiple regions. This will increase the speed of our app.
  • Dedicated Cluster – A dedicated cluster is a single server only dedicated to our organization/project. It can provide advanced performance.
  • Shared Cluster – Shared Clusters are dedicated to a number of users. So it will affect the performance of our app in peak timings.

Because we are in a development mode, Shared Cluster is ok for us. It is Free.

It will direct to another page and from here, we can choose the Provider and Region, RAM etc.

We can choose from AWS, Google Cloud, and Azure.

Because we are not choosing a paid plan, create a cluster with default settings which is free.

4. Create a collection

So the cluster is created and now we need to create a collection. We discussed that a cluster is a server for storing our project databases.

A collection is simply the collection of databases associated with each project we are going to create. A cluster can contain multiple collections.

So from the cluster we created, click on the COLLECTIONS tab.

We will get an option to load a Sample Dataset and our own data. Choose Add My Own Data from the options.

This will open up a modal for creating a database. I am giving posts as database name and posts and collection names.

5. Connect to the cluster

Now we can look for the steps to connect this database with our backend application. For this, we need a connection string.

Before getting a connection string, we need to complete some steps.

At the top-right, we can see a tab Cmd Line Tools. Click on it, and it will show us a page as below.

Click the Connect Instructions button.

It will display a view as below, where we should choose the option Connection your application.

For setting up the connection securely, we can set an IP address of the server where our backend is running. So that the request to the database can only be done from the server.

But in our case, we are developing our backend locally. So, let us choose, Add your current IP Address. So that we can use the database locally.

Note that, if a number of developers are accessing the DB from different IP addresses, Choosing the option Allow access from Anywhere is preferred.

Now we can create a database username and password. This data will be used in our connection string to maintain a secure access.

At the next screen, we will get a connection string that can be added to the backend code for connecting the database with the backend.

Create an Express backend

So we have created a MongoDB cloud database. Now let us create a Node or Express backend. I have already written an article about creating a simple express backend. The link to this article is given below.

How To Build A Simple REST API With Node/Express

The above article will explain each steps in details to create and Express backend.

File structure

The file structure of the express project we are going to build is given below. It contains an index.js file, models, and routes.

1. Create a schema for the post

We need a schema for each post to create. So create Post.js modal inside models directory. A post should contain the fields,

  • title
  • description
  • author
  • timestamps.

Below code will explain the complete Post.js modal.

2. Create a route for posts

Now we need to create a route called posts.js that contains all the CRUD operations of posts.

It contains,

  • A POST method for creating posts.
  • GET method for listing all posts.
  • GET method for fetching a single post with “postId“.
  • PUT method for updating a single post with “postId“.
  • DELETE method for deleting a single post.

3. Create a config file to add the connection string to DB

This is one of the important step in this article. Here, we are adding the connection string that we got after creating the MongoDB Atlas cloud database.

This connection string will look as below. Here we must replace the string “password” with the password we generated on step 5.

mongodb+srv://techomoro:password@cluster0.7cpxz.mongodb.net/posts?retryWrites=true&w=majority

So that the complete config.js file looks the same as below.

4. Create an index file

Now, we will create an index.js file in the root directory to handle all the routes and database connections.

Here we will import all necessary packages, the config file, and the route file posts.js we have set up before.

Then define a port number also. The backend will start in this port number.

5. Add a starting script in package.json

This step simplifies starting the backend. We can start the app by executing nodemon index.js. By adding this script inside our package.json file, we can start our backend with a simple command npm start.

So start our backend using the below command.

npm start

Test the created APIs using Postman

So we have created a MongoDB Atlas cloud database, an Express backend and connected them. Now we can test the entire the backend APIs we have created using Postman tool.

We can use the below link to download the Postman tool.

https://www.postman.com/downloads/

1. Create a new post

We can create a new post by sending a POST request to the below API URL.

http://localhost:3031/posts

The request should contain a JSON body as below.

{
    "title": "This is title of the new post5",
    "description": "This is description of the new post5",
    "author": "Anu"
}

If the request is successful, it creates a new post in our database and send a response as below.

{
    "status": 200,
    "data": {
        "_id": "6081aac14a213fcbf0e7955c",
        "title": "This is title of the new post5",
        "description": "This is description of the new post5",
        "author": "Anu",
        "createdAt": "2021-04-22T16:56:33.297Z",
        "updatedAt": "2021-04-22T16:56:33.297Z",
        "__v": 0
    }
}

2. List all posts

The below API end point can be used to get the list of posts we have created.

http://localhost:3031/posts/list

3. Get a post details

We can get the details of a single post with its id. Place a GET request to the below API endpoint for this.

http://localhost:3031/posts/60812b5d5e262dca2b42e8e7

4. Update a post

A post can be updated with its id. Placing a PUT request to the below API will do this.

http://localhost:3031/posts/60812b5d5e262dca2b42e8e7

The request should contain a JSON body as below.

{
    "author": "Mithun"
}

5. Delete a post

We can delete a post by placing a DELETE request to the API below.

http://localhost:3031/posts/60812d76a8ad93ca917d6efe

GitHub repository

You can always refer to the GitHub repository to clone the backend we have made.

https://github.com/syamjayaraj/posts-backend

Summary

So we came to an end. In this article, we learned the steps to create and set up a MongoDB Atlas cloud database, created a new Express backend, and set up REST APIs. We have also tested the APIs using the Postman tool.

Be the first to reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.