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

后端 未结 2 1547
[愿得一人]
[愿得一人] 2021-02-03 15:36

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/expre

相关标签:
2条回答
  • 2021-02-03 15:43

    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
    });
    
    0 讨论(0)
  • 2021-02-03 15:50

    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});
    
    0 讨论(0)
提交回复
热议问题