通过javascript从mongodb中设置的辅助副本中读取 [英] Read from secondary replica set in mongodb through javascript

查看:89
本文介绍了通过javascript从mongodb中设置的辅助副本中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个mongo实例在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:不是master和slaveOk = false]
名称:"MongoError",
消息:不是主从" =否",
好的:0,
errmsg:不是主服务器和从属服务器Ok = false",
代码:13435}

{ [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');

我想念什么?

推荐答案

由于您正在尝试从数据库级别的辅助服务器读取数据.您应该在副本集的连接URL中将readPreferences指定为"secondaryPreferred".

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.

使用MongoDB Node.JS驱动程序读取首选项

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

这篇关于通过javascript从mongodb中设置的辅助副本中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆