node.js mongodb 如何连接到 mongo 服务器的副本集 [英] node.js mongodb how to connect to replicaset of mongo servers

查看:72
本文介绍了node.js mongodb 如何连接到 mongo 服务器的副本集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中使用 mongonode.js.mongo 数据库由两台服务器组成.

I am using mongo and node.js in an application. The mongo database consists of two servers.

http://howtonode.org/express-mongodb 中给出的示例中,我可以连接到一台服务器使用:

In the example given in http://howtonode.org/express-mongodb, i can connect to one server using:

ArticleProvider = function(host, port) {
 var database = 'node-mongo-blog';
 this.db= new Db(database, new Server(host, port, {auto_reconnect: true}, {}));
 this.db.open(function(){});
};

但是我如何连接到多个服务器,在我的情况下有两个服务器.

But how can I connect to multiple servers, in my case there are two servers.

推荐答案

示例代码来自https://github.com/christkv/node-mongodb-native/blob/master/examples/replSetServersQueries.js.

指定的服务器只是种子列表 - 它会自动发现完整列表.副本集的成员不是静态的 - 它们会发生变化(可能会添加新服务器或可能会删除现有服务器).客户端连接到输入列表中指定的服务器之一,然后从中获取副本集成员.因此,您不必在此处列出所有服务器地址 - 如果列表中提到的至少一台服务器已启动并正在运行,它会自动查找其余服务器.

The servers specified is only the seed list - it will discover the complete list automatically. The member of a replica set are not static - they will change (a new server might get added or an existing server might be removed). The client connects to one of the servers specified in the input list and then fetches the replica set members from that. So you don't have to list all the server addresses here - if at least one of the servers mentioned in the list is up and running it will find the rest automatically.

var port1 = 27018;
var port2 = 27019;
var server = new Server(host, port, {});
var server1 = new Server(host, port1, {});
var server2 = new Server(host, port2, {});
var servers = new Array();
servers[0] = server2;
servers[1] = server1;
servers[2] = server;

var replStat = new ReplSetServers(servers);
console.log("Connecting to " + host + ":" + port);
console.log("Connecting to " + host1 + ":" + port1);
console.log("Connecting to " + host2 + ":" + port2);
var db = new Db('node-mongo-examples', replStat, {native_parser:true});

这篇关于node.js mongodb 如何连接到 mongo 服务器的副本集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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