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

后端 未结 2 1554
[愿得一人]
[愿得一人] 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
    });
    

提交回复
热议问题