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.
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 .
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').
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With