I have a mongo replica including one primary two secondaries. There are some accounts only have access to the secondary server. When I connect to one of the secondary through nodejs driver, I couldn't find a way to enable slaveOk
. Below is my code. I have to connect to it as a normal server rather than a replica.
options = options || {
connectTimeoutMS: 30000,
socketTimeoutMS: 30000,
// retry to connect for 30 times
reconnectTries: 30,
// wait 1 second before retrying
reconnectInterval: 1000,
readPreference: mongodb.ReadPreference.SECONDARY_PREFERRED
};
mongoClient.connect("mongodb://user:[email protected]/test", options, (err, db) => {
db.command({listCollections: 1})
.catch((e) => {
// get exception here about "not master and slaveOk=false"
})
}
when I run above code, I will get the exception saying that not master and slaveOk=false
. I know that I need to enable slaveOk
on the connection before run db.command({listCollections: 1})
but I didn't find a way for that.
I know there is a readPreference
on options but I have tried below values none of them work:
ReadPreference.PRIMARY,
ReadPreference.PRIMARY_PREFERRED,
ReadPreference.SECONDARY,
ReadPreference.SECONDARY_PREFERRED,
ReadPreference.NEAREST
In Mongo Shell, I can run rs.slaveOk()
command to enable read on the connection on secondary server. Is there a way to enable slaveOk
on nodejs driver? So I can run listCollection
command through dirver.
Connect your Node. js applications to MongoDB and work with your data using the Node. js driver. The driver features an asynchronous API that you can use to access method return values through Promises or specify callbacks to access them when communicating with MongoDB.
To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });
Connect to a Single MongoDB Instanceconst MongoClient = require('mongodb'). MongoClient; const assert = require('assert'); // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'myproject'; // Use connect method to connect to the server MongoClient.
What worked for me was putting the read prefences argument as ?readPreference=secondaryPreferred
into the connect
url.
Read from secondary replica set in mongodb through javascript has a more complete example.
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