Check mongoose connection state without creating new connection

I use this for my Express Server mongoDB status, where I use the express-healthcheck middleware

// Define server status
const mongoose = require('mongoose');
const serverStatus = () => {
  return { 
     state: 'up', 
     dbState: mongoose.STATES[mongoose.connection.readyState] 
  }
};
//  Plug into middleware.
api.use('/api/uptime', require('express-healthcheck')({
  healthy: serverStatus
}));

Gives this in a Postman request when the DB is connected.

{
  "state": "up",
  "dbState": "connected"
}

Gives this response when the database was shutdown.

{
"state": "up",
"dbState": "disconnected"
}

(The "up" in the responses represent my Express Server status)

Easy to read (no numbers to interpret)


Since the mongoose module exports a singleton object, you don't have to connect in your test.js to check the state of the connection:

// test.js
require('./app.js'); // which executes 'mongoose.connect()'

var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);

ready states being:

  • 0: disconnected
  • 1: connected
  • 2: connecting
  • 3: disconnecting