简体   繁体   中英

mongodb db.open() returns replicaset error but no error in mongodb log files

NodeJS version: v0.10.29 Mongo version: 2.6.3 NodeJS mongodb module: 1.4.5

We are getting the following error in the callback to db.open

"Error: No valid replicaset instance servers found"

The mongodb seems to be working fine and there is no error in the mongodb logs. Restarting the nodejs server solves the problem.

From https://github.com/HabitRPG/habitrpg/issues/2725 :

One of the odd things about the Node driver is that the default timeout for replica set connections is only 1 second, so make sure you're setting it to something more like 30s like in this example:

{ 
   options: { 
      replset: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }, 
      server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } } 
   } 
}

I think they meant these as options for use with MongoClient() .

I have seen this error when starting both a MongoDB cluster and Node.js at the same time.

As MongoDB replica sets require to elect a primary and do other hand shaking activities when they are started this can introduce a delay in the MongoDB instances being available to connect to. Making the issue you describe more likely to occur.

Increasing the timeout values on the connection, as rakslice's answer details, can prevent this.

It is worth referring to the official MongoDB documentation for connection timeout settings and explanation:

To add rakslice's answer here is a full example of how you might connect to a replset with connection timeout values set:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://localhost:27017,localhost:27017,localhost:27017/test", 
        {
            replset: { 
                socketOptions: { 
                    connectTimeoutMS: 30000 
                } 
            },
            server: {
                    socketOptions: {
                        connectTimeoutMS: 500
                    }
                }
        }, 
        function(err, db) {
                if (err) throw err;

                db.collection("things").find({}).toArray(function(err, docs) {
                    if (err) throw err; 

                console.log(docs);
                    db.close();         
                });
        }
);

A good article that goes over some of the implications & decisions of setting a particular timeout value(s):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM