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 of Node.js, Express.js, and MongoDB. We will create a simple express backend and use the 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 MongoDB Atlas 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 step by step with screenshots and explanations.

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.

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.

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.

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.

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 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. Refer to it if you have any doubts.

Here, we are going to create a simple 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.

Create a schema for the post

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

  • title
  • description
  • author
  • timestamps.

The code below is the complete Post.js modal file.

// models/Post.js

const mongoose = require("mongoose");
let Schema = mongoose.Schema;

let postSchema = new Schema(
  {
    title: {
      type: String,
    },
    description: {
      type: String,
    },
    author: {
      type: String,
    },
  },
  { timestamps: true }
);

let Post = mongoose.model("post", postSchema);

module.exports = Post;

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.
// routes/posts.js

const express = require("express");
const Post = require("../models/Post");
const router = express.Router();

router.post("/", async (req, res) => {
  try {
    let post = new Post(req.body);
    post = await post.save();
    res.status(200).json({
      status: 200,
      data: post,
    });
  } catch (err) {
    res.status(400).json({
      status: 400,
      message: err.message,
    });
  }
});

router.get("/list", async (req, res) => {
  try {
    let posts = await Post.find();
    res.status(200).json({
      status: 200,
      data: posts,
    });
  } catch (err) {
    res.status(400).json({
      status: 400,
      message: err.message,
    });
  }
});

router.get("/:postId", async (req, res) => {
  try {
    let post = await Post.findOne({
      _id: req.params.postId,
    });
    if (post) {
      res.status(200).json({
        status: 200,
        data: post,
      });
    }
    res.status(400).json({
      status: 400,
      message: "No post found",
    });
  } catch (err) {
    res.status(400).json({
      status: 400,
      message: err.message,
    });
  }
});

router.put("/:postId", async (req, res) => {
  try {
    let post = await Post.findByIdAndUpdate(req.params.postId, req.body, {
      new: true,
    });
    if (post) {
      res.status(200).json({
        status: 200,
        data: post,
      });
    }
    res.status(400).json({
      status: 400,
      message: "No post found",
    });
  } catch (err) {
    res.status(400).json({
      status: 400,
      message: err.message,
    });
  }
});

router.delete("/:postId", async (req, res) => {
  try {
    let post = await Post.findByIdAndRemove(req.params.postId);
    if (post) {
      res.status(200).json({
        status: 200,
        message: "Post deleted successfully",
      });
    } else {
      res.status(400).json({
        status: 400,
        message: "No post found",
      });
    }
  } catch (err) {
    res.status(400).json({
      status: 400,
      message: err.message,
    });
  }
});

module.exports = router;

Create a config file to store the connection string to MongoDB Atlas

This is one of the important steps in this article. Here, we are adding the connection string copied from MongoDB Atlas.

This connection string will look as below. Here you must replace the string username, password, and database name from our MongoDB Atlas.

Here the credentials I am using are:-

  • username: techomoro
  • password: password
  • database/collection name: posts
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.

// config.js

let config = {
  dbUrl:
    "mongodb+srv://techomoro:[email protected]/posts?retryWrites=true&w=majority",
};

module.exports = config;

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 with this port number.

// index.js

const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
const mongoose = require("mongoose");

mongoose.set("useNewUrlParser", true);
mongoose.set("useFindAndModify", false);
mongoose.set("useCreateIndex", true);

const port = 3031;
const config = require("./config");

const postsRouter = require("./routes/posts");

app.use(logger("dev"));

const dbUrl = config.dbUrl;

var options = {
  keepAlive: 1,
  connectTimeoutMS: 30000,
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

mongoose.connect(dbUrl, options, (err) => {
  if (err) console.log(err);
});

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use("/posts", postsRouter);

app.listen(port, function () {
  console.log("Runnning on " + port);
});
module.exports = app;

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.

{
  "name": "express-backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongoose": "^5.9.25",
    "morgan": "^1.10.0"
  }
}

So that we can 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 backend APIs we have created using the Postman tool.

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

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

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 back 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
    }
}

List all posts

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

http://localhost:3031/posts/list

A GET request to be above API will respond with the JSON result as below.

Get a post details

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

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

This will returns the details of the post with _id, 60812b5d5e262dca2b42e8e7.

Update a post

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

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

The request should contain a JSON body as below.

{
    "author": "Mithun"
}

This will update the author of the post and returns the new post details.

Delete a post

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

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

This will delete the post with id, 60812d76a8ad93ca917d6efe and returns a success message.

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, create a new Express backend, and set up REST APIs. We have also tested the APIs using the Postman tool.

2 thoughts on “Connect MongoDB Atlas with Express Backend

    1. If you are using mongoose 6 these options are unnecessary.

      So, remove the lines from index.js

      mongoose.set(“useNewUrlParser”, true);
      mongoose.set(“useFindAndModify”, false);
      mongoose.set(“useCreateIndex”, true);

Leave a Reply

Your email address will not be published.

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