-
-
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(); |
If we use just one
mongoose.connect( ... )
//mongoose bug this event is never delivered
mongoose.connection.on('reconnect', function (ref) {
connected=true;
console.log('reconnected to mongo server.');
});
//This event is delivered (!) so using it!
mongoose.connection.db.on('reconnect', function (ref) {
connected=true;
console.log('reconnected to mongo server.');
});
If we use your retry loop - even the event that gets delivered does not
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.)
Yes this solves the initial connect, but we found that it causes another side effect. On further db hiccups the reconnect event is not delivered by mongoose (if this pattern is used) :-( So for now we have taken the route of simply issuing mongoose.connect() (but checking if the server can reach the db in the start scripts). It is mandatory to do those checks in start scripts anyways ..