How to ensure Node.js keeps running after MonogDB connection drops? How to ensure Node.js keeps running after MonogDB connection drops? mongoose mongoose

How to ensure Node.js keeps running after MonogDB connection drops?


This is what I do to deal with Mongo failing - add it as middleware. It will also try to reconnect again.

// Handler in case Mongo  goes downapp.use(function(req, res, next) {  // We lost connection!  if (1 !== mongoose.connection.readyState) {    // Reconnect if we can    mongoose.connect(config.db, options);    res.status(503);    throw new Error('Mongo not available');  }  next();});

This assume you have a standard 50x error handler somewhere that will show a nice page to the user.

The reconnect is there for the next user/page load to check if it's back up. Works nice.


Try initializing the DB in a domain, that would catch the errors without crashing

var d = require('domain').create();d.on('error', function(er) {    console.log('Oh no, something wrong with DB');});d.run(function() {    mongoose.connect(config.db, options);});

It's generally a good idea to let the server restart when something crashes, but as you're already aware of this and want to avoid it, wrapping whatever fails in domains is the way to do it.


The MongoDB driver issues a "close" event when the connection is lost. You can tap on this event and flag the DB as unavailable and write any logic based on that.

db.on('close', function() {  // handle the disconnect  dbAvailable = false;});

I've got a small NPM module that handles this if you are interested: https://npmjs.org/package/mongoconnect