strange mongodb and mongoose error: not master and slaveOk=false error
I solved this by simply fixing the URI my Node.js application was using to connect to MongoDB with Mongoose.
When this error ocurred, my URI was
mongodb://user:password@host:port/datatabase
,
and this was giving me the error not master and slaveOK=false.
Then I changed the URI to add the Replica Set information, and the URI became something like this:
mongodb://user:password@host:port,replicaSetHost:replicaSetPort/database?replicaSet=rs-someServer
.
Now, I don't know if this is a general pattern, because this configuration is the one used by MongoLab, which is where my DataBase is hosted. However, it's likely you will solve the problem by adding the replica set information in the URI as well.
That means you're trying to read from a secondary node in a replica set, you can only read from the primary node by default.
You can allow a secondary node to accept reads by running rs.slaveOk()
in a mongo shell that is connected to that secondary node. Allowing reads from a secondary is not recommended, because you could be reading stale data if the node isn't yet synced with the primary node.
UPDATE: As Janusz Slota's comment points out, rs.slaveOk()
is no longer used. Use rs.secondaryOk()
instead, however this is still not recommended. Here's the documentation for rs.secondaryOk().