Check if mongoDB is connected

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.


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()

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();