The Better Async Way to Connect to MongoDB in NodeJs

You may need to be sure that your application is connected to MongoDB before the run anything else. So let’s make the connection code more useful.

In case of the MongoDB still not run you will get a connection error, like that:

MongoNetworkError: failed to connect to server [mongodb:27017] on first connect

To prevent the application has been broken, let’s modify the connection code in the this way:

const mongo = require('mongodb').MongoClient;

var db;

const options = { useNewUrlParser: true };

const mongoConnect = () => {

  mongo.connect(process.env.MONGODB_URI, options)
    .then(client => {

      console.log("Connected to MongoDB.");

      db = client.db(process.env.MONGODB_DBNAME);
    })
    .catch(err => {

      console.log('MongoDB connection unsuccessful, retry after 5 seconds.');

      setTimeout(mongoConnect, 5000);
    })
}

mongoConnect()

To be sure that we really established the connection and we could run the dependent code, let’s write the code in the async way:

const mongo = require('mongodb').MongoClient;

var db;

const options = { useNewUrlParser: true };

const mongoConnect = async () => {
  return new Promise((resolve, reject) => {

    mongo.connect(process.env.MONGODB_URI, options)
      .then(client => {

        console.log("Connected to MongoDB.");

        db = client.db(process.env.MONGODB_DBNAME);
      })
      .catch(err => {

        console.log('MongoDB connection unsuccessful, retry after 5 seconds.');

        setTimeout(mongoConnect, 5000);
      })

  })
}

const start = async () => {

  mongoConnect()
  .then(db => {

    console.log("Connected to MongoDB.");

    // So, now we could run the other code...
  })
}

start()