3

I am trying to read from a slave node but I get the following error.

MongoError: not master
    at Function.MongoError.create (node_modules/mongodb-core/lib/error.js:31:11)
    at node_modules/mongodb-core/lib/topologies/server.js:777:66
    at Callbacks.emit (node_modules/mongodb-core/lib/topologies/server.js:95:3)
    at null.messageHandler (node_modules/mongodb-core/lib/topologies/server.js:249:23)
    at Socket.<anonymous> (node_modules/mongodb-core/lib/connection/connection.js:265:22)
    at emitOne (events.js:78:13)
    at Socket.emit (events.js:170:7)
    at readableAddChunk (_stream_readable.js:147:16)
    at Socket.Readable.push (_stream_readable.js:111:10)
    at TCP.onread (net.js:524:20)

Here is my code

var MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb://slave.example.com/?slaveOk=true', {slaveOk: true}, (err, db) => {
   if (err) { throw err }
   d = db.db('order', {server: {slaveOk: true}})
   d.eval('rs.slaveOk(); 1', (err, data) => {
     if (err) { throw err }
     console.log(data);
   })
})

I am providing the complete list of hosts in the connection string because the node that is running this query only has access to the secondary MongoDB nodes.

When using the command line interface I am able to make queries as long as I run rs.slaveOk() before executing my query.

1 Answer 1

3

you can simply using below code

var collection1 = db.collection(currentCollection,{readPreference:'secondaryPreferred'});

for more details check Scaling Read Query Load

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.