在Node.js项目中连接多个Mongo DB

时间:2018-01-04 18:21:02

标签: javascript node.js mongodb express mongoose

我正在尝试将多个MongoDB数据库连接到一个Node.js项目中。这是我目前的结构和问题。

节点版本: v6.12.1

Express.js版本: 4.16.2

猫鼬版本: 4.13.6

当前结构:

primaryDB.js

var mongoose = require('mongoose');
var configDB = require('./database.js');


//Connect to MongoDB via Mongoose
mongoose.Promise = require('bluebird');

//mongoose.Promise = global.Promise;
mongoose.connect(configDB.url, { useMongoClient: true });


//Check for successful DB connection
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Primary DB Successfully Connected..");
});

module.exports = mongoose;

secondaryDB.js

var mongoose = require('mongoose');

mongoose.connect('mongodb://mongodb_address_goes_here:27017/db_name', { useMongoClient: true });

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Secondary DB Successfully Connected..");
});


module.exports = mongoose;

然后将每个数据库连接分别导入其模式文件,模式文件从模式文件中导出模块。

手头的问题

当我运行我的应用程序时它启动正常并成功连接到两个DB但是我相信mongoose要么被覆盖了,要么因为我可以在主要上执行findOne()命令但是次要失败,反之亦然

示例:

var async = require('async');
var primaryModel = require('../../../models/general/primary');
var SecondaryModel = require('../../../models/general/secondary');


function getInfo() {

  async.waterfall([
    getPrimaryName,
    getSecondaryName
  ], function (err, info) {
  });
};

function getPrimaryName(callback){
  Primary.findOne({}, function (err, primaryInfo){
    if (err) {
      console.log("Error" + err);
    }
      console.log('Primary info is : ' + primaryInfo);
     callback(null,primaryInfo);
  });
}



function getSecondaryName(primaryInfo, callback) {
  
  console.log(primaryInfo); //Make sure its being passed

  Secondary.findOne({}, function (err, secondaryInfo) {
    if (err) {
      console.log("Error" + err);
    }
    console.log('Secondary Info is  : ' + secondaryInfo);
    callback(null, secondaryInfo);
  });
}

上面的问题是我可能会从调用Primary而不是Secondary调用数据。我再次相信这是被某种被覆盖的东西。

任何帮助表示赞赏。对于详细程度感到抱歉。

1 个答案:

答案 0 :(得分:2)

使用mongoose.createConnection创建您的连接

所以

const conn1 = mongoose.createConnection('first server options')
const conn2 = mongoose.createConnection('second server options')

在这里阅读更多内容 http://mongoosejs.com/docs/connections.html#multiple_connections