Open In App

How to wait for MongoDB connection to be made before creating HTTP server in Node.js?

Last Updated : 25 Mar, 2022
Like Article

Connecting your server to is a database a very crucial task in back-end development as the database is the location where the user-provided data will be stored until further action is taken.

If we fail to connect to the database before creating the server, whatever data is being processed by the server will not get stored in the database. So, as a result, the data is inserted by the client-side will not be persisting in nature.

Here in this article, we will create a server using Node.js (more specifically using Express) and we will connect our server to a MongoDB database using mongoose ODM.

Express is an open-source, minimal, and robust Node.js web framework used to build web applications and APIs (Application Programming Interface).

To run an express server on your computer, make sure Node.js is installed in your system. To check whether Node.js is installed or not  type the below command in the terminal: 

node -v

If it shows the version of Node.js installed in your system, just like the screenshot below move on to the next step.

Project installation and folder structure:

Step 1: Create a separate GFG folder in your system and navigate to this folder using the command prompt.

mkdir GFG & cd GFG

Step 2: Create a package.json file within the folder using the following command:

npm init

Step 3: Create an index.js file in the root directory, this is the file that will start the server. Install express and mongoose package using the following command :

npm install express mongoose

Step 4: Create a connect.js file in the root directory, this is file where the code regarding database connection will be written. 

Project Structure: It will look like this. Create connect.js and index.js files as shown below.

Server initialization and process of database connection:

If MongoDB is not installed in your local system, follow this link. Create a database named DEMO_DB(name it according to your wise) using the following command:


We will use mongoose in this article which is an ODM(Object Document Mapper) for Node.js. To know more about it, follow this link. Now write down the following code in respective files.


const mongoose = require("mongoose");
const connectDB = (URL) => {
    return mongoose.connect(URL, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
module.exports = connectDB;


const Express = require("express");
const connectDB = require("./connect");
const app = Express();
const PORT = 8000;
// Basic route for testing
app.get("/", (req, res) => {
    res.send("welcome to the server.");
const start = async () => {
    try {
        await connectDB("mongodb://localhost:27017/DEMO_DB");
        app.listen(PORT, () => {
            console.log(`Server is running on port ${PORT}.`);
    } catch (error) {
        console.log("Failed to connect to the database, 
            server is not running.");

Step to run the application: Stop the server running using (Ctrl+C) command in the terminal, then restart the server using the following command:

node index.js

Output: Open the browser and type http://localhost:8000 and we will get the following response.

If this is the response we are getting, then the database has been properly connected to the server by it has been created.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads