如何在nodejs mongodb驱动程序中使用mongoclient设置read Preference secondary?

时间:2016-07-04 12:47:01

标签: node.js mongodb

我正在使用mongodb副本集。我有以下配置:

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);

});

我使用以下nodejs代码连接db name myapplicationDb:

使用mongodb驱动程序版本1.4.38。

 if (!file_exists('NamFdr1/NamFdr2/NamFdr3')) 
 {
     mkdir('NamFdr1/NamFdr2/NamFdr3', 0777, true);
 }

我想设置read Preference secondary。

但所有读取操作都在主数据库上执行。 如何设置?

1 个答案:

答案 0 :(得分:0)

此代码解决了我的问题:

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);

});