Skip to content

Instantly share code, notes, and snippets.

@taf2
Created July 1, 2011 15:51
Show Gist options
  • Save taf2/1058819 to your computer and use it in GitHub Desktop.
Save taf2/1058819 to your computer and use it in GitHub Desktop.
mongoose node.js reconnect code
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);
@weisjohn
Copy link

It seems to be the line 25, mongoose.connection.db.close(); seems to trigger it's own event...?

@weisjohn
Copy link

Thanks very much for this! Totally saved my day!

@fizerkhan
Copy link

Mongoose has support for auto_reconnect. By default, it sets to true. Why do we need to write reconnect manually?

@itoonx
Copy link

itoonx commented Jul 31, 2015

When i used mongoose for auto_reconnect. By default , I have a problem.
mongo has many connection. guild me pls.

@kdmon
Copy link

kdmon commented Jun 27, 2016

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

@lauramorillo
Copy link

@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));

@nishatmazhar
Copy link

@lauramorillo,
I am using setTimeout to continuously try to connect on disconnect.

ex:

  1. 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)
}
});
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment