简体   繁体   中英

node.js mongodb how to connect to replicaset of mongo servers

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

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.

The accepted answer is quite old now. Since then a lot has changed. You can use a connection string in this format:

mongodb://[username:password@]host1[:port1][,...hostN[:portN]]][/[database][?options]]

An example would look like this:

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

Sample code from 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});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM