我在用mongo
and node.js
在一个应用程序中。 mongo数据库由两台服务器组成。
在给出的例子中http://howtonode.org/express-mongodb http://howtonode.org/express-mongodb,我可以使用以下方式连接到一台服务器:
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(){});
};
但是我如何连接到多个服务器,在我的例子中有两台服务器。
接受的答案现在已经很旧了。从那时起,很多事情都发生了变化。您可以使用连接字符串 https://docs.mongodb.com/manual/reference/connection-string/以这种格式:
mongodb://[用户名:密码@]主机1[:端口1][...主机N[:端口N]]][/[数据库][?选项]]
一个例子如下:
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
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)