I have seen many questions on the same regard but somehow I still can't successfully connect to MongoDB Slave.
I am running my cluster on Kubernetes using mongo-k8s-sidecar, connecting my application directly to the master works fine, however whenever I try to connect to the slave, I can't seem to read, here's error code:
MongoError: not master and slaveOk=false
I am using Node.js for my application, and this is how I am connecting:
var mongodb = require('mongodb').Db;
var Server = require('mongodb').Server
var db = new mongodb('dbname', new Server("localhost",27017,{slaveOk: true}));
db.open(function(err, conn){
if (err){
callback(err);
}else {
client=conn;
client.createIndex("tablename", {field:1}
, {background:true}, function(err, i) {
logger.info(err);
});
//The rest of the code is trimmed
What am I missing here?
You can't run createIndex()
on a Secondary member, even if you're using slaveOk/ReadPreference.SECONDARY.
If you test the code without the createIndex()
call, you'll probably see that it's working as you expect.
See Build Indexes on Replica Sets for more details. Basically, if you wanted to build an index on a secondary you need to stop the mongod instance, start it as a standalone (without the replSet option), then build the index.
Or you can only create the index on the Primary, and the index creation will replicate to the secondaries.
Assuming you are using v1.x of the driver, slaveOk: true
is an option of the db, not the server:
var db = new mongodb('dbname', new Server("localhost",27017), {slaveOk: true});
For v2.x driver the option is readPreference=ReadPreference.SECONDARY
.