我正在尝试使用 mongodb 节点模块连接多个数据库。 我试过了,一切正常。但是我不确定我是否使用了正确的方法。 注意:我正在尝试使用2个副本(mongo-db1.com和mongo-db2.com)将不同服务器中的数据库连接起来
db.js
var MongoClient = require('mongodb').MongoClient;
const mongolab_uri = "mongodb://username:password@mongo-db1.com:27017,mongo-db2.com:27017/";
module.exports.init = function () {
MongoClient.connect(mongolab_uri+'users?authSource=admin&replicaSet=test-rs', function (err, client) {
if (err) {
console.log(err);
return
}
module.exports.user = client.collection('user');
module.exports.client = client.collection('client');
console.log('db -1');
})
MongoClient.connect(mongolab_uri + 'company?authSource=admin&replicaSet=test-rs', function (err, client) {
if (err) return
module.exports.info = client.collection('info');
module.exports.details = client.collection('details');
console.log('db -2');
});
MongoClient.connect(mongolab_uri + 'shop?authSource=admin&replicaSet=test-rs', function (err, client) {
if (err) return
module.exports.list = client.collection('list');
module.exports.customers = client.collection('customers');
console.log('db -3');
})
}
index.js
var db = require('db.js');
db.init();
app.listen(3000, function(){
console.log('server started');
})
api.js
var db = require('db.js');
var collection = db.customers;
collection.find({ users: id}).toArray(function(err, customers) {
if(err) throw err;
console.log(customers)
});