-
-
Save taf2/1058819 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose'); | |
var db = mongoose.connect("mongodb://localhost/testdb"); | |
var reconnTimer = null; | |
function tryReconnect() { | |
reconnTimer = null; | |
console.log("try to connect: %d", mongoose.connection.readyState); | |
db = mongoose.connect("mongodb://localhost/testdb"); | |
} | |
mongoose.connection.on('opening', function() { | |
console.log("reconnecting... %d", mongoose.connection.readyState); | |
}); | |
mongoose.connection.on('open', function() { | |
console.log("connected"); | |
if (reconnTimer) { clearTimeout(reconnTimer); reconnTimer = null; } | |
}); | |
mongoose.connection.db.on('close', function() { | |
console.log("disconnected"); | |
mongoose.connection.readyState = 0; // force... | |
mongoose.connection.db.close(); // removeAllListeners("reconnect"); | |
if (reconnTimer) { | |
console.log("already trying"); | |
} | |
else { | |
reconnTimer = setTimeout(tryReconnect, 500); // try after delay | |
} | |
}); | |
process.on('SIGINT', process.exit.bind(process)); | |
setInterval(function() { | |
console.log('alive: %d', mongoose.connection.readyState); | |
},2500); |
As others have pointed out, reconnecting is now baked into mongoose and enabled by default. But it might be useful to know that Mongoose by default will only try reconnecting for 30s and then give up. Set the server.reconnectTries
option to increase the number of times mongoose will try to reconnect. For example, you can tell mongoose to never stop trying to reconnect like this:
mongoose.connect(uri, { server: { reconnectTries: Number.MAX_VALUE } });
See connection docs and server options defaults for details
@kadmon I have tried using that configuration but even with it when I kill my database I get a disconnected event and when I start my database again, it never connects back, any idea regarding what could be wrong?
mongoose.connect(connStr, { server: { reconnectTries: Number.MAX_VALUE } })
.then(() => log.info('Connected to database!'))
.catch(err => log.error(err));
@lauramorillo,
I am using setTimeout to continuously try to connect on disconnect.
ex:
- Attach event handler
instance.connection.on("disconnected", () => {
console.log("Databse disconnected: ");
if (connected) {
connected = false;
console.log("After disconnect");
tryPersistentDbConnection(dbSettings, connectUrl, mongoose, { server: { auto_reconnect: false } });
}
});
private static tryPersistentDbConnection(dbSettings, connectUrl, mongoose, options) {
var instance = mongoose.connect(connectUrl, options, function (err) {
if (err) {
console.log("Error connecting. Error Message: " + err.message);
console.log("------------Trying to reconnect------------------");
setTimeout(function () {
//call itself on failure
tryPersistentDbConnection(dbSettings, connectUrl, mongoose, options)
}, 25000)
}
});
}
When i used mongoose for auto_reconnect. By default , I have a problem.
mongo has many connection. guild me pls.