Read from secondary replica set in mongodb through javascript
Asked Answered
J

2

2

I have 2 mongo instance running in 2 different servers (one primary and other secondary); I am able to retrieve a document from the primary server using this connection code:

var db = mongojs('user:pswd@localhost:27017/mydb?authSource=admin');

But when I try to retrieve a document from the secondary server, I am getting the following error:

{ [MongoError: not master and slaveOk=false]
name: 'MongoError',
message: 'not master and slaveOk=false',
ok: 0,
errmsg: 'not master and slaveOk=false',
code: 13435 }

I also tried using the code:

var db = mongojs('user:pswd@localhost:27017/mydb?authSource=admin&slaveOk=true');

What am I missing?

Juncaceous answered 29/9, 2016 at 11:36 Comment(0)
C
6

Since you are trying to read from Secondary at DB level. You should specify the readPreferences "secondaryPreferred" in the connection URL for your replica set.

You can refer this document which describes in detail how to do that.

Read Preferences with MongoDB Node.JS Driver

var MongoClient = require('mongodb').MongoClient
  , format = require('util').format;

var url = format("mongodb://%s,%s,%s/%s?replicaSet=%s&readPreference=%s"
  , "localhost:27017",
  , "localhost:27018"
  , "localhost:27019"
  , "exampleDb"
  , "foo"
  , "secondaryPreferred");

MongoClient.connect(url, function(err db) {
  if(!err) {
    console.log("We are connected");
  }
});
Crooked answered 29/9, 2016 at 12:4 Comment(0)
T
0
MongoClient.connect(
  'mongodb://ip/mongo-primary:27017,ip/mongo-secondary-1:ip/mongo-secondary-2:27017,ip/mongo-secondary-3:27017?readPreference=secondaryPreferred',
  {useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) { var db = client.db('viajydb'); 

db.collection('customers').findOne({}, function (findErr, result) { if (findErr) throw findErr; console.log(result.name); client.close(); }); });
Tiffanietiffanle answered 22/7, 2020 at 18:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.