node.js - how to set read Preference secondary using mongoclient in nodejs mongodb driver? -
i using mongodb replica set. have following config :
{ "members": [ { "host": "db1.example.com", "port": "27017" }, { "host": "db2.example.com", "port": "27017" } ] }
i connecting db name myapplicationdb using following nodejs code :
using mongodb driver version 1.4.38.
var mongoclient = require('mongodb').mongoclient; var server = require('mongodb').server; var url = 'mongodb://'; var options = { server: { slaveok: true, readpreference: server.read_secondary, socketoptions: {"connecttimeoutms": 30000} }, db: { readpreference: server.read_secondary }, replset: { rs_name: "replicaname", readpreference: server.read_secondary } } members.foreach(function (member) { url = url + member.host + ':' + member.port + ',' }); url = url.substring(0, url.length - 1); url += '/' + "myapplicationdb"; mongoclient.connect(url, options, function (err, db) { console.log("db >>>>>>>>", db); });
i want set read preference secondary.
but read operations executing on primary db. how set ?
this code solve problem :
var mongoclient = require('mongodb').mongoclient; var server = require('mongodb').server; var url = 'mongodb://'; var options = { //server: { // slaveok: true, // readpreference: server.read_secondary, // socketoptions: {"connecttimeoutms": 30000} //}, //db: { // readpreference: server.read_secondary //}, //replset: { // rs_name: "replicaname", // readpreference: server.read_secondary //} } members.foreach(function (member) { url = url + member.host + ':' + member.port + ',' }); url = url.substring(0, url.length - 1); url += '/' + "myapplicationdb"; url = url + "?replicaset=replicaname&readpreference=secondarypreferred&connecttimeoutms=30000" mongoclient.connect(url, options, function (err, db) { console.log("db >>>>>>>>", db); });
Comments
Post a Comment