-
-
Save asalant/4092454 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose') | |
var mongoUrl = "mongodb://localhost:27017/test" | |
var connectWithRetry = function() { | |
return mongoose.connect(mongoUrl, function(err) { | |
if (err) { | |
console.error('Failed to connect to mongo on startup - retrying in 5 sec', err); | |
setTimeout(connectWithRetry, 5000); | |
} | |
}); | |
}; | |
connectWithRetry(); |
Mongoose uses the native nodejs mongodb drive which has as of version 1.4.9 options for retrying connections. So you're probably just duplicating the effort.
retryMiliSeconds {Number, default:5000}, number of milliseconds between retries.
numberOfRetries {Number, default:5}, number of retries off connection.
http://mongodb.github.io/node-mongodb-native/api-generated/db.html
Zambonilli, those options work but only when the connection is lost at runtime. They do not help if the initial connection fails.
I opened an issue for this concern here.
We use something similar to the workaround above, but we don't want to reconnect on every Error (since as Zambonilli mentioned, the driver is capable of handling runtime reconnections automatically). So in our case, we only retry the connect in the specific case of a "first connect" error:
if (err.message && err.message.match(/failed to connect to server .* on first connect/)) {
setTimeout(...);
}
(We actually do this inside db.on('error'
and we use db.open(dbURL).catch(() => {});
inside our setTimeout. We ignore the rejections because they appear to get passed to the error handler anyway.)
If we use just one
If we use your retry loop - even the event that gets delivered does not