javascriptnode.jsmongodbexpressmongoose

Connecting Multiple Mongo DBs in a Node.js Project


I am trying to connect multiple MongoDB databases into a single Node.js project. Here is my current structure and issue at hand.

Node Version: v6.12.1

Express.js Version: 4.16.2

Mongoose Version: 4.13.6

Current Structure:

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;

Then each DB connection gets imported respectively into their schema files, from which the schema files have module exports.

Issue at hand

When I run my application it starts fine and connects to both DB's successfully however I believe that mongoose is either getting overwritten or something because I might be able to do a findOne() command on primary but secondary fails or vice versa.

Example:

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

The problem with above is I might get data back from the call to Primary but not Secondary. Which again I believe is from something being overridden .

Any help appreciated. Sorry about the verbosity.


Solution

  • use mongoose.createConnection to create your connections

    so

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

    read more here http://mongoosejs.com/docs/connections.html#multiple_connections