Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check mongoose connection state without creating new connection

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?

like image 869
cyberwombat Avatar asked Oct 25 '13 21:10

cyberwombat


People also ask

Does Mongoose close connection automatically?

You should close a mongoose connection when a Node POSIX signal is happening. SIGINT process is triggered when Ctrl-C has been pressed on terminal or a server shutdown. Another possible scenario is to close a connection when a data streaming is done.

Does Mongoose keep connection open?

But generally speaking, Mongoose is keeping several socket connections open to the server/replica-set/mongos instances rather than one to allow concurrent processing of requests.

How do I know if MongoDB is connected node?

isConnected runs getDbObject . getDbObject connects to mongoDB and returns an object: connected (true/false), db (dbObject or error). Then, isConnected resolve/reject by connected property.


1 Answers

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
like image 50
robertklep Avatar answered Oct 16 '22 02:10

robertklep