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, 
            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";


CODE: DB Query


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

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

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://[email protected]/melvingeorge/nodejsmongorssample.git

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

1 Answer 1


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.

  • I have given auto_reconnect to be true, still have the same issue. Jan 31, 2015 at 10:09
  • To be sure that is not your driver but the database, try to test using pymongo that supports auto_reconnect 100%. If the pymongo wont work then start looking the database.
    – Antonios
    Jan 31, 2015 at 13:39
  • its not the problem with auto_reconnect, I think azure is force closing the connection when its idle for more than 4 mins or so. that makes the issue. I think. its not handled in mongodb drivers. Feb 24, 2016 at 4:38
  • This has nothing to do with Azure. I wonder is newer versions of mongoose handle this properly Apr 16, 2021 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.