<p>I have seen many questions on the same regard but somehow I still can't successfully connect to MongoDB Slave.</p>

<p>I am running my cluster on Kubernetes using <a href="https://github.com/cvallance/mongo-k8s-sidecar" rel="nofollow noreferrer">mongo-k8s-sidecar</a>, 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:</p>

<p><code>MongoError: not master and slaveOk=false</code></p>

<p>I am using Node.js for my application, and this is how I am connecting:</p>

<pre><code>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
</code></pre>

<p>What am I missing here?</p>

<p>You can't run <code>createIndex()</code> on a Secondary member, even if you're using slaveOk/ReadPreference.SECONDARY.</p>

<p>If you test the code without the <code>createIndex()</code> call, you'll probably see that it's working as you expect.</p>

<p>See <a href="https://docs.mongodb.com/manual/tutorial/build-indexes-on-replica-sets/" rel="nofollow noreferrer">Build Indexes on Replica Sets</a> 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.</p>

<p>Or you can only create the index on the Primary, and the index creation will replicate to the secondaries.</p>
