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

Tuco picture Tuco · Sep 12, 2012 · Viewed 16.3k times · Source

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.

Answer

Felipe picture Felipe · Feb 28, 2019

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