Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 935
Tuco Avatar asked Sep 12 '12 09:09

Tuco


People also ask

How does MongoDB connect to replicaSet?

To connect to a replica set deployment, specify the hostname and port numbers of each instance, separated by commas, and the replica set name as the value of the replicaSet parameter in the connection string. In the following example, the hostnames are host1 , host2 , and host3 , and the port numbers are all 27017 .

How do I connect to Sharded cluster?

To connect to a sharded cluster, specify the mongos instance or instances in the URI connection string. In the following example, the connection string specifies the mongos instances running on localhost:50000 and localhost:50001 and the database to access ( myproject ). var MongoClient = require('mongodb').


1 Answers

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
});
like image 67
Felipe Avatar answered Oct 10 '22 22:10

Felipe