Prabhu Kathiresan Prabhu Kathiresan - 2 months ago 17
Node.js Question

Read from secondary replica set in mongodb through javascript

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

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


And when i try to retrieve document from secondary server, I am getting the follwing error

error console

I also tried using the code

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


What am I misssing??
Thanks in advance

Answer

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");
  }
});
Comments