28

I have mongoDB in my app.

I want to check if mongoDB is connected, before I listen to the app.

Is it the best way for doing it?

This is my server.js file:

var express = require('express');
var mongoDb = require('./mongoDb');
var app = express();

init();

function init() {
    if (mongoDb.isConnected()) {
      app.listen(8080, '127.0.0.1');
    }
    else {
      console.log('error');
    }
}

isConnected runs getDbObject. getDbObject connects to mongoDB and returns an object: connected (true/false), db (dbObject or error).

Then, isConnected resolve/reject by connected property.

This is mongoDb.js file:

//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');
// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/myDb';

var connectingDb; // promise

//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;

init();

module.exports = {
    isConnected: isConnected
}

// Use connect method to connect to the Server
function init() {
  connectingDb = new Promise(
    function (resolve, reject) {
      MongoClient.connect(url, function (err, db) {
        if (err) {
          console.log('Unable to connect to the mongoDB server. Error:', err);
          reject(err);
        }
        else {
          console.log('Connection established to', url);

          //Close connection
          //db.close();
          resolve(db);
        }
      });

    }
  );
}

function getDbObject() {
  return connectingDb().then(myDb => {
                                       return {
                                          connected: true,
                                          db: myDb
                                        }
                                      }
                              )
                       .catch(err =>  {
                                        return {
                                          connected: false,
                                          db: err
                                        }
                                      }
                             )
}

function isConnected() {
    return new Promise(
        function(resolve, reject) {
          var obj = getDbObject();
          if (obj.connected == true) {
            console.log('success');
            resolve(true);
          }
          else {
            console.log('error');
            reject(false);
          }
        }
    )

}

Any help appreciated!

3

4 Answers 4

15

there are multiple ways depends on how your DB is configured. for a standalone (single) instance. You can use something like this

Db.connect(configuration.url(), function(err, db) {
  assert.equal(null, err);

if you have a shared environment with config servers and multiple shards you can use

db.serverConfig.isConnected()
1
  • 2
    This is not true anymore from 4.0, now connect() is a noop in case an existing connection is present. Commented Mar 11 at 7:49
12

Let client be the object returned from MongoClient.connect:

let MongoClient = require('mongodb').MongoClient
let client = await MongoClient.connect(url ...
...

This is how i check my connection status:

function isConnected() {
  return !!client && !!client.topology && client.topology.isConnected()
}

This works for version 3.1.1 of the driver. Found it here.

2
  • 2
    This returns true, but if I try to insertOne in a collection, I get UnhandledPromiseRejectionWarning: MongoError: server instance pool was destroyed. I'd like to test for this as well. Commented Sep 30, 2019 at 9:58
  • 3
    This does not work when using useUnifiedTopology: true when connecting, it will always return true Commented Oct 24, 2019 at 3:56
11

There has been some changes since version 3, isConnected is no longer available in version 4. The correct way of dealing with an ambiguous connection is to just call MongoClient.connect() again. If you're already connected nothing will happen, it is a NOOP or no-operation, and if there is not already a connection you'll be connected (as expected). That said, if you really want to know if you have a connection try something like this:


const isConnected = async (db) => {

    if (!db) {
        return false;
    }

    let res;

    try {
        res = await db.admin().ping();
    } catch (err) {
        return false;
    }

    return Object.prototype.hasOwnProperty.call(res, 'ok') && res.ok === 1;
};


4

From version 3.1 MongoClient class has isConnected method. See on https://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#isConnected

Example:

const mongoClient = new MongoClient(MONGO_URL);

async function init() {
  console.log(mongoClient.isConnected()); // false
  await mongoClient.connect();
  console.log(mongoClient.isConnected()); // true
}
init();
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.