Search code examples
mongodbmongoosecommandreplicaset

how to use conn.db.admin().command() on secondary in replica set?


Trying to get results of command that I passed in admin command, but it throws me back a MongoError

how to/ where to set rs.slaveOk() using mongoose lib, if its ?

conn = mongoose.createConnection(`mongodb://localhost:port`)
cmd = "someCommand"
conn.db.admin().command(cmd, (err, result)=>{
if(err){
console.error(err) 
}
resolve(result)
})
// MongoError: not master and slaveOk=false

Solution

  • Added Read Preference and Replicaset name in Connection String

    https://mongoosejs.com/docs/connections.html#connection-string-options https://mongoosejs.com/docs/api.html#query_Query-read

    var options = {
         "db": {
         "readPreference": "secondaryPreferred"
         },
         "replset": {
             "rs_name": "replica_name",
         }
     }
    
     var connection = 
     mongoose.createConnection(`mongodb://localhost:27030/dbname`, options);