mongodb, replicates and error: { “$err” : “not master and slaveOk=false”, “code” : 13435 }

前端 未结 8 1460
遥遥无期
遥遥无期 2020-11-30 17:24

I tried mongo replica sets for the first time.

I am using ubuntu on ec2 and I booted up three instances. I used the private IP address of each of the instances. I p

8条回答
  •  半阙折子戏
    2020-11-30 17:46

    I got here searching for the same error, but from Node.js native driver. The answer for me was combination of answers by campeterson and Prabhat.

    The issue is that readPreference setting defaults to primary, which then somehow leads to the confusing slaveOk error. My problem is that I just wan to read from my replica set from any node. I don't even connect to it as to replicaset. I just connect to any node to read from it.

    Setting readPreference to primaryPreferred (or better to the ReadPreference.PRIMARY_PREFERRED constant) solved it for me. Just pass it as an option to MongoClient.connect() or to client.db() or to any find(), aggregate() or other function.

    • https://docs.mongodb.com/v3.0/reference/read-preference/#primaryPreferred
    • http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html (search readPreference)
    const { MongoClient, ReadPreference } = require('mongodb');
    const client = await MongoClient.connect(MONGODB_CONNECTIONSTRING, { readPreference: ReadPreference.PRIMARY_PREFERRED });
    

提交回复
热议问题