Mongoose connection events and reconnecting to MongoDB

I’ve seen many methods to have mongoose reconnect to mongo after an error. This is a huge problem, especially if the network drops for even a second. In our app, mongoose didn’t even know the connection had dropped, and our application would not be able to reach the database. To fix this, we had to force mongoose to reconnect on it’s own. Note: scroll to bottom for the fix, the next section is just for notes.

Our Old Method


// check ready state
if(mongoose.connection.readyState){

   // force disconnect and reconnect in a few seconds
   mongoose.disconnect();
   setTimeout(function(){
      mongoose.connect(url, options);
   },5000);

}

However, usually the mongoose.connection.readyState variable is not accurate. In my situation, it was always 1 – connected, even when it was disconnected such as if the network dropped for a second. Even an interval constantly checking mongoose.connection.readyState would not work, because it never changed.

Mongoose 4.9.4 has a new connection event called timeout which helped out a lot because it was fired when error was not.
Mongoose connection events – connected, disconnecting, disconnected, reconnected, error, timeout, close


    mongoose.connect(url,options);

    mongoose.connection.on('error', function(e){
        console.log("db: mongodb error " + e);
        // reconnect here
    });

    mongoose.connection.on('connected', function(e){
        console.log('db: mongodb is connected: ' + url);
    });

    mongoose.connection.on('disconnecting', function(){
        console.log('db: mongodb is disconnecting!!!');
    });

    mongoose.connection.on('disconnected', function(){
        console.log('db: mongodb is disconnected!!!');
    });

    mongoose.connection.on('reconnected', function(){
        console.log('db: mongodb is reconnected: ' + url);
    });

    mongoose.connection.on('timeout', function(e) {
        console.log("db: mongodb timeout "+e);
        // reconnect here
    });

    mongoose.connection.on('close', function(){
        console.log('db: mongodb connection closed);
    });

Best Answer

With the newer versions of mongoose and mongo, here’s the quickest fix. It seems to be reconnecting on its own.


mongoose.connect(url, 
   {
      server: { 
         auto_reconnect: true,
         reconnectTries: Number.MAX_VALUE,
         reconnectInterval: 1000,
         socketOptions: {keepAlive: 1, connectTimeoutMS: 30000}
      } 
   }
);

All of the event functions and manually reconnecting are not needed if the mongoose auto reconnect is working for you. By default it only tries a few times, which may be why it never worked in the past.

Share this:

One comment, add yours.

swdev

thanks, it’s a lot of help!

Leave a comment