Mongoose populate across 2 databases

瘦欲@ 提交于 2021-02-08 13:58:10

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/35571546/mongoose-populate-across-2-databases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!