簡體   English   中英

node.js mongodb如何連接到mongo服務器的replicaset

[英]node.js mongodb how to connect to replicaset of mongo servers

我在應用程序中使用mongonode.js mongo數據庫由兩個服務器組成。

http://howtonode.org/express-mongodb中給出的示例中,我可以使用以下命令連接到一台服務器:

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(){});
};

但是我如何連接到多個服務器,在我的情況下有兩個服務器。

接受的答案現在很老了。 從那以后,很多都發生了變化。 您可以使用以下格式的連接字符串

MongoDB的:// [用戶名:密碼@]主機1 [:端口1] [,... hostN [:端口n] [?選項]] [/ [數據庫]

一個例子看起來像這樣:

const { MongoClient } = require('mongodb');

const connectionString = 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/admin?replicaSet=myRepl';

MongoClient.connect(connectionString, options).then((client) => {
    const db = client.db('node-mongo-blog');
    // do database things
}).catch((error) => {
    // handle connection errors
});

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

指定的服務器只是種子列表 - 它將自動發現完整列表。 副本集的成員不是靜態的 - 它們將更改(可能會添加新服務器或可能刪除現有服務器)。 客戶端連接到輸入列表中指定的其中一個服務器,然后從中獲取副本集成員。 因此,您不必在此列出所有服務器地址 - 如果列表中提到的至少一個服務器已啟動並運行,則會自動查找其余服務器。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM