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