In Mongoosejs, how to detect and set a timeout for a database connection is lost?

If the DB connection is lost, node will continue to search for the connection to the database like crazy.

So, is it possible to set the connection to repeat # or timeout if the connection is lost? and throw errors .. instead of continuing the loop and trying to connect

mongoose.connect (DB_PATH);

+4
source share
1 answer

This may not exactly answer your question, but you can say that Mongoose is not trying to reconnect by passing the auto_reconnect parameter to the server. This will prevent the database from trying automatically.

 mongoose.connect(mongodb_url, { server : { auto_reconnect : true } }); 

Then in your code, you can manually check the connection status as follows:

 if ( mongoose.connection.readyState == 0 ) { // disconnected // reconnect } 

See other connection ready states: https://github.com/LearnBoost/mongoose/blob/master/lib/connection.js#L38

+1
source

All Articles