Created
October 3, 2014 08:24
-
-
Save eiriklv/a7204bb6325860487850 to your computer and use it in GitHub Desktop.
Mongoose error handling and automatic reconnect
This file contains hidden or 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 debug = require('debug')('mongoose-setup') | |
module.exports.db = function (mongoose, config){ | |
function connect() { | |
mongoose.connect(config.get('mongo_url')); | |
} | |
// connection is open and ready | |
mongoose.connection.on('open', function (ref) { | |
debug('open connection to mongo server.'); | |
}); | |
// mongoose is connected to server | |
mongoose.connection.on('connected', function (ref) { | |
debug('connected to mongo server.'); | |
}); | |
// mongoose has disconnected | |
mongoose.connection.on('disconnected', function (ref) { | |
debug('disconnected from mongo server.'); | |
debug('retrying connection in 2 seconds..'); | |
setTimeout(function() { | |
connect(); | |
}.bind(this), 2000); | |
}); | |
// mongoose connection has closed | |
mongoose.connection.on('close', function (ref) { | |
debug('closed connection to mongo server'); | |
}); | |
// error has occured for mongoose connection | |
mongoose.connection.on('error', function (err) { | |
debug('error connection to mongo server!'); | |
debug(err); | |
}); | |
// mongoose is reconnecting | |
mongoose.connection.on('reconnect', function (ref) { | |
debug('reconnect to mongo server.'); | |
}); | |
// initial connect | |
connect(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment