Akercode.com

Test Mongoose Connection with readyState

There are different ways to test a mongoose database connection with the mongoose.connection.readyState, where the output is a number representing one of the following statuses:

  • 0: disconnected
  • 1: connected
  • 2: connecting
  • 3: disconnecting
mongoose.connect(`mongodb://${server}/${database}`, { useNewUrlParser: true })
  .then(() => {
    console.log('Successfully connected to MongoDB!');
  })
  .catch(err => {
    console.log('Connection failed', err);
  });

console.log(mongoose.connection.readyState);

Output:

2 // connecting..

You could add an event listener on a specific status with a callback function:

mongoose.connect(`mongodb://${server}/${database}`, { useNewUrlParser: true });

// Fires when the status is 1: connected
mongoose.connection.on('connected', function() {
  console.log('A connection has been established!');
});

// Fires when the status is 0: disconnected
mongoose.connection.on('disconnected', function() {
  console.log('No connection was found!');
});

It can be useful to add the status to it's own endpoint so you can check the connection any time you want:

app.get('/api/healthcheck', (request, response) => {
  response.json({ info: mongoose.connection.readyState })
})

Output:

{"info":1}

Or even better get the actual state..

app.get('/api/healthcheck', (request, response) => {
  response.json({ info: mongoose.STATES[mongoose.connection.readyState] })
})

Output:

{"info":"connected"}