murvinlai
murvinlai

Reputation: 50375

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

if DB connection is lost, node will keep looking for the DB connection like crazy.

so, is there an option to set the # of connection retry, or timeout if connection lost? and throw errors.. instead of keep looping and trying to connect

mongoose.connect(db_path);

Upvotes: 4

Views: 1157

Answers (1)

Bryan Clark
Bryan Clark

Reputation: 2602

This might not exactly answer you question but you can tell Mongoose to not try reconnecting by passing the auto_reconnect option to the server. That will prevent it trying the DB automatically.

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

Then in your code you could manually check for the connection state like this:

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

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

Upvotes: 1

Related Questions