2016-07-04 37 views
1

我正在使用mongodb副本集。我有以下配置:如何设置读取首选使用mongoclient在nodejs mongodb驱动程序?

{ 
"members": [ 
     { 
     "host": "db1.example.com", 
     "port": "27017" 
     }, 
     { 
     "host": "db2.example.com", 
     "port": "27017"    
     } 
    ]  
} 

我使用连接数据库名称myapplicationDb以下代码的NodeJS:

使用MongoDB的驱动程序版本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); 

}); 

我想设置读取偏好次要。

但是所有读操作都在主db上执行。 如何设置?

回答

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

}); 
相关问题