I had the same question as you, and robertklep’s solution didn’t work for me either. I found when MongoDB service is stopped, an error event is triggered, but the connection.readyState is still 1 (connected). That may be why it didn’t auto reconnect.
This is what I have now:
var db = mongoose.connection;
db.on('connecting', function() {
console.log('connecting to MongoDB...');
});
db.on('error', function(error) {
console.error('Error in MongoDb connection: ' + error);
mongoose.disconnect();
});
db.on('connected', function() {
console.log('MongoDB connected!');
});
db.once('open', function() {
console.log('MongoDB connection opened!');
});
db.on('reconnected', function () {
console.log('MongoDB reconnected!');
});
db.on('disconnected', function() {
console.log('MongoDB disconnected!');
mongoose.connect(dbURI, {server:{auto_reconnect:true}});
});
mongoose.connect(dbURI, {server:{auto_reconnect:true}});