How to check Node.js Mongoose connection state without creating a new connection?

Sometimes, we want to check Node.js Mongoose connection state without creating new connection.

In this article, we’ll look at how to check Node.js Mongoose connection state without creating new connection.

How to check Node.js Mongoose connection state without creating a new connection?

To check Node.js Mongoose connection state without creating new connection, we can use the mongoose.connection.readyState property.

For instance, we write

const mongoose = require('mongoose');

console.log(mongoose.connection.readyState);

The possible values for mongoose.connection.readyState include:

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

Conclusion

To check Node.js Mongoose connection state without creating new connection, we can use the mongoose.connection.readyState property.