MongoDB error not master and slaveOk=false on primary node with mongoose

Viewed 7708

I'm running a replicated mongoDB and I can connect to the master DB in the set no problem using mongo:

bash-4.2$ mongo --port 25023
MongoDB shell version: 3.2.6
rs0:PRIMARY>

But when using mongoose like this:

mongoose.connect('mongodb://127.0.0.1:25023/XXX', { useNewUrlParser: true });

I get:

XXX/node_modules/mongoose/lib/utils.js:452       
throw err;
    ^
MongoError: not master and slaveOk=false
   at queryCallback (/XXX/node_modules/mongodb-core/lib/cursor.js:247:25)

The suggestion was to do this:

mongodb://user:password@host:port,replicaSetHost:replicaSetPort/database?replicaSet=rs-someServer.

But that is a bit unwieldly. Is there no way to tell mongoose we are connecting to a master server and not a slave?

Second problem ... Even listing the other hosts didn't work:

mongoose.connect('mongodb://localhost:P,S1:P,S2:P/XXX?replicaSet=rs0', { useNewUrlParser: true });

I get this error even though I supplied the replicaSet:

(node:13757) UnhandledPromiseRejectionWarning: Unhandled promise rejection  (rejection id: 1): MongoError: seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name

Here is where it gets strange: I CAN make this work. If I use this line:

mongoose.connect('mongodb://127.0.0.1:25023/XXX', { useNewUrlParser: true });

And let it fail, and then touch a JS file forcing a NodeJS restart, then it seems to start working?

1 Answers

Same issue, basically I wanted to connect to the primary node in a replica set (write concern), but I was intermittently connecting to a secondary node (race condition).

Solution / TLDR;

Add ?replicaSet=test&w=majority to your MONGO_URL connection string.


From the documentation...

Replica Set with a High Level of Write Concern

The following connects to a replica set with write concern configured to wait for replication to succeed across a majority of the data-bearing voting members, with a two-second timeout.

NOTE

For a replica set, specify the hostname(s) of the mongod instance(s) as listed in the replica set configuration.

mongodb://example1.com,example2.com,example3.com/?replicaSet=test&w=majority&wtimeoutMS=2000
Related