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.
you can simply using below code
var collection1 = db.collection(currentCollection,{readPreference:'secondaryPreferred'});
for more details check Scaling Read Query Load
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With