Check mongoose connection state without creating new connection

cyberwombat picture cyberwombat · Oct 25, 2013 · Viewed 54.3k times · Source

I have some tests - namely Supertest - that load my Express app. This app creates a Mongoose connection. I would like to know how to check the status of that connection from within my test.

In app.js

mongoose.connect(...)

In test.js

console.log(mongoose.connection.readyState);

How to access the app.js connection? If I connect using the same parameters in test.js will that create a new connection or look for existing one?

Answer

robertklep picture robertklep · Oct 26, 2013

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