Mongodb – Failing to automatically re-connect to New PRIMARY after a replica set failover , from Mongoose (MongoDB, NodeJS Driver)

mongodb

I made a simple NodeJS App, with Mongoose as MongoDB Driver. And connected to a mongodb replica set. The App is working fine until I shut down the current primary, When the PRIMARY is down, the replica set automatically elected a new PRIMARY. But, after that the node application doesn't seems to be responding for DB queries.

CODE: DB Connection

var options = { 
    server: { 
        socketOptions: { 
            keepAlive: 1, 
            connectTimeoutMS:30000, 
            socketTimeoutMS:90000 } 
        },
    replset: { 
        socketOptions: { 
            keepAlive: 1, 
            connectTimeoutMS : 30000 , 
            socketTimeoutMS: 90000  
        }, 
        rs_name: 'rs0' 
     } };

var uri = "mongodb://xxx.xxx.xxx.xxx:27017,xxx.xxx.xxx.xxx:27017,xxx.xxx.xxx.xxx:27017/rstest";

 mongoose.connect(uri,options);

CODE: DB Query

  router.('/test',function(req,res){

     var testmodel = new testModel('test') ;
     testmodel.save(function (err, doc,numberAffected) {
         if (err) {
             console.log("ERROR: "+ err);
             res.status = 404;
             res.end;
         }else{
             console.log("Response sent ");
             res.status = 200;
             res.end;
         }
     });
 });

Steps Followed

  1. Created a MongoDB replica set in three VMs.
  2. Created a simple nodeJS App (Express + Mongoose) with a test API as above
  3. Sent GET request to 'test' continuously with some time interval to the app from a local system.
  4. Took the PRIMARY instance down
  5. APPLICATION STOPPED RESPONDING TO REQUESTS

Varsions:
"express": "4.10.6",
"mongodb": "1.4.23",
"mongoose": "3.8.21",

A sample app that I have done for debugging this issue is available at https://melvingeorge@bitbucket.org/melvingeorge/nodejsmongorssample.git

I am not sure if this is a bug or some mis-configuration from my end. How to solve this issue ?

Best Answer

You need something like the flag { auto_reconnect: true } as described here http://mongodb.github.io/node-mongodb-native/api-generated/db.html.

According to documentation: The server option auto_reconnect is defaulted to true which can be overridden.