Joey Yi Zhao
Joey Yi Zhao

Reputation: 42500

How to set slaveOk on MongoDB through nodejs driver?

I have a mongo replica including one primary two secondaries. There are some accounts only have access to the secondary server. When I connect to one of the secondary through nodejs driver, I couldn't find a way to enable slaveOk. Below is my code. I have to connect to it as a normal server rather than a replica.

options = options || {
        connectTimeoutMS: 30000,
        socketTimeoutMS: 30000,
        // retry to connect for 30 times
        reconnectTries: 30,
        // wait 1 second before retrying
        reconnectInterval: 1000,
        readPreference: mongodb.ReadPreference.SECONDARY_PREFERRED
      };
mongoClient.connect("mongodb://user:[email protected]/test", options, (err, db) => {
    db.command({listCollections: 1})
       .catch((e) => {
         // get exception here about "not master and slaveOk=false" 
       })
}

when I run above code, I will get the exception saying that not master and slaveOk=false. I know that I need to enable slaveOk on the connection before run db.command({listCollections: 1}) but I didn't find a way for that. I know there is a readPreference on options but I have tried below values none of them work:

ReadPreference.PRIMARY, 
ReadPreference.PRIMARY_PREFERRED, 
ReadPreference.SECONDARY, 
ReadPreference.SECONDARY_PREFERRED, 
ReadPreference.NEAREST

In Mongo Shell, I can run rs.slaveOk() command to enable read on the connection on secondary server. Is there a way to enable slaveOk on nodejs driver? So I can run listCollection command through dirver.

Upvotes: 7

Views: 3232

Answers (1)

Andrew Lipscomb
Andrew Lipscomb

Reputation: 1056

What worked for me was putting the read prefences argument as ?readPreference=secondaryPreferred into the connect url.

Read from secondary replica set in mongodb through javascript has a more complete example.

Upvotes: 8

Related Questions