问题描述
我有一个使用 2 个数据库的 node app
.一个是 Names
,另一个是所有数据的其余部分.
I have a node app
that uses 2 databases. One is the the Names
and the other for the rest of all the data.
我有这个连接设置:
// 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'
此连接工作正常.
将数据保存到 app_db
和 names_db
也没有问题.
There's also no problem upon saving data to both app_db
and names_db
working perfect.
但问题是:当我尝试查询例如 Account
模型,然后填充引用的 Name
模型时,填充过程返回 null代码>.
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
.
帐户架构:
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);
名称架构:
'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);
查询和人口:
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
}
})
是否有一种特殊的方法可以将 db1 中的数据填充到 db2 中的数据中?谢谢.
Is there a special way to populate data from db1 the data from db2? Thanks.
推荐答案
跨数据库填充 Mongo 文档 功能自 mongoose v3.9.0
起添加.根据这个 , 调用 model
时应该使用不同的数据库名称.一些示例代码如下.更多详情请参考链接中的测试代码.
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('name', '', Name)
这篇关于Mongoose 跨越 2 个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!