Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose populate across 2 databases

I have a node app that uses 2 databases. One is the the Names and the other for the rest of all the data.

I have this connection setup:

// DATABASE CONNECTION
var APP_DB_URI = config.APP_DB; // mongodb://localhost:27017/app_db
var app_DB = mongoose.createConnection(APP_DB_URI);
var name_DB = app_DB.useDb(config.NAME_DB); // 'name_db'

This connection is working properly.

There's also no problem upon saving data to both app_db and names_db working perfect.

But the problem is this: when I try to query let say the Account model and then populate the referenced Name model, the populate process returns null.

Account schema:

 var mongoose = require('mongoose');
 var Schema = mongoose.Schema;
 var field = {
     email: {type: String, unique: true},
     password: {type: String, select: false},
     name: {type: Schema.Types.ObjectId, ref: 'Name'},
 }

 var options = {
     id: false,
     versionKey: false
 }

 var schema = new Schema(field, options);
 module.exports = mongoose.model('Account', schema);

Name schema:

 'use strict';

 var mongoose = require('mongoose'); 
 var Schema = mongoose.Schema;

 var field = {
     firstName: {type: String, required: true},
     middleName: {type: String, required: true},
     lastName: {type: String, required: true},
     suffix: {type: String, required: false,},
 }

 var options = {
     id: false,
     versionKey: false
 }

 var schema = new Schema(field, options);
 module.exports = mongoose.model('Name', schema);

The query and population:

var app_db = *app_db instance passed to this controller*    

var Account = app_db.model('Account');

Account.findOne({email:req.body.email})
    .populate('name')
    .exec(function (err, user) {
        if(user){
            // user.name returns null
        }
    })

Is there a special way to populate data from db1 the data from db2? Thanks.

like image 940
CENT1PEDE Avatar asked Feb 23 '16 07:02

CENT1PEDE


1 Answers

Populate Mongo documents across databases feature added since mongoose v3.9.0. Per this across db populate test, you should different db name when model is called. Some sample codes as below. More details please refer to the test codes in the link.

var app_DB = mongoose.createConnection(APP_DB_URI);
var name_DB = app_DB.useDb(config.NAME_DB); // 'name_db'

// ...
module.exports = app_DB.model('Account', schema);

// ...
module.exports = name_DB.model('Name', schema);

Populate

.populate('name', '', Name)
like image 65
zangw Avatar answered Oct 19 '22 12:10

zangw