Connect MongoDB to Express Application

Connect MongoDB to Express Application

Introduction

MongoDB is a very popular database choice for backend developers. The primary reason is that it is a NoSQL database, and it is easy to store and manipulate data in MongoDB. Since MongoDB is a NoSQL database, data is stored in the form of serializable objects. An example is given below

{
"name": "John Doe",
"email": "johndoe@gmail.com",
"profession": "Stand-Up Comic"
}

This serializable form is very efficient in storing and manipulating data. You can find more information on the official website. Let's find out how to connect MongoDB with our Express application.

Starting with our Express application

The first step we have to complete is to create and set up our project directory. You can do this by following my previous article in this backend development series. It provides a full guide on how to initialize an empty Node project. You can find the article here.

Once our application has been initialized, we can continue with this article.

Writing the function for connecting

After the application has been set up, all we need is to define a function for connecting MongoDB to our Express application. We shall use the mongoose package for connecting with our Database. As I have mentioned in my previous article, the folder named config shall contain all our configuration files.

Therefore, let's make a config file called db.config.ts which shall contain the configuration code for connecting to our database.

Now, which database should we connect to?

Since we are connecting to MongoDB, therefore we need a MongoDB cluster and a connection link to that cluster. If you visit the MongoDB website and follow this article to create a MongoDB cluster, you are good to go. For connecting to Mongo, you will need the connection string, which is in the form of

mongodb+srv://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

Once you get the connection string, store it in your .env file, where it will be safe, and the connection string will not be made public so easily.

With that out of the way, let's focus now on writing the code.

In the db.config.ts file, all you need to do is write the following code:

import mongoose, { CallbackError } from "mongoose";

export const connect = mongoose.connect(
    String(process.env.MONGO_URI),
    {},
    (err: CallbackError) => {
        if (err) console.error(err);
        else console.log("DB connection successful");
    }
);

This is a very simple code, the mongoose.connect() function takes 3 parameters, the first one being the connection string of MongoDB, then some optional parameters, which you can choose to keep blank, and finally a callback function.

Where to call this function

You have to connect to MongoDB before making any API requests. Therefore, this function must be executed before everything else. Hence, in the app.ts, you need to call the function like this:

import dotenv from "dotenv";
dotenv.config();

import express, { Application } from "express";
import cors from "cors";
import { connect } from "./config/db.config";

const app: Application = express();

app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

const port: number = Number(process.env.PORT) || 5000

app.get("/", async (req, res) => {
    res.send(`API running successfully since ${new Date()}`);
});

app.listen(port, () => {
    console.log(`Server started listening to ${port}`);
    connect;
});

The app.listen() function is the first function to be executed when we start our backend server. Therefore, we can call the connect function in the callback function of app.listen(), this makes sure that we are connected to the database even before any API requests are made.

Conclusion

This brings us to the end of this article. In this article, we have learned, how to connect a MongoDB database cluster to our Express application.

Keep learning, and keep building!


Follow me on:

Also, if you like my content, do subscribe to my newsletter so that whenever I publish a new article, it gets delivered to your email, and you get notified.