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

Created on 15 Feb 2019  路  4Comments  路  Source: Automattic/mongoose

mongoose: v4.13.6
node: v8.9.0

help

All 4 comments

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

Set the readPreference option in your connection string:
https://mongoosejs.com/docs/connections.html#connection-string-options
https://mongoosejs.com/docs/api.html#query_Query-read

  • edit: I'm using MongoDB with docker image in my production base*.

Trying with replicaSet connection string using readPreference. But didn't connect on the production server, its throw me back an error:

Note: 1> the below code working fine with a success message in/with my local machine.
2> i have checked rs.conf the hostname is same as in error message "test-machine:27018"

name: 'MongoError', message: 'failed to connect to server [test-machine:27018] on first connect [MongoError: getaddrinfo ENOTFOUND test-machine:27018 test-machine:27018]'

var mongoose = require('mongoose') //version 4.13.6

var options = { "db": {
        "readPreference": "secondaryPreferred"
    },
    "replset": {
        "rs_name": "testReplica",
    }
}

var connection = mongoose.createConnection(`mongodb://localhost:27018/`,options);

connection.on('open', function () {
    console.log('We are connected')
})

connection.on('error', function (err) {
    console.log('Something went wrong')
    console.log(err)
})

@VishalBheda this is a dns resolution error. Make sure your docker image can resolve the dns name. You may need to add test-machine to your /etc/hosts file

Was this page helpful?
0 / 5 - 0 ratings