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