Created
November 17, 2012 01:24
-
-
Save asalant/4092454 to your computer and use it in GitHub Desktop.
Retry connecting to mongo if initial connect fails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
(We actually do this inside
db.on('error'
and we usedb.open(dbURL).catch(() => {});
inside our setTimeout. We ignore the rejections because they appear to get passed to the error handler anyway.)