【发布时间】:2018-07-13 14:10:20
【问题描述】:
我已经为名为 associates 和 outlets 的 mongoose 创建了两个模式。
出口架构:-
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var OutletSchema = new Schema(
{
associate_id: {type: ObjectId, max: 100 },
city_id:{type:ObjectId, max: 100},
outlet_name: {type: String, max: 100},
oulet_address: {type: String, max: 500},
outlet_contact: {type: String, minlength: 9, maxlength: 12 },
active: {type: Boolean}`enter code here`
}`
);
module.exports = mongoose.model('Outlet', OutletSchema);
关联架构:-
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
ObjectId = Schema.ObjectId;
var AssociateSchema = new Schema(
{
associate_name: {type: String, max: 100},
associate_address: {type: String, max: 500},
associate_contact: {type: String, minlength: 9, maxlength: 12 },
associate_email: {type: String, max: 100},
active: {type: Boolean}
}
);
module.exports = mongoose.model('Associate', AssociateSchema);
这些是我创建的架构。
我如何使用 relationship() 填充员工中的出口
我已经尝试过下面给出的代码。
router.get('/getUsingPopulate', function (req, res) {
data = {}
Associate.relationship({path:'outlet', ref:'Outlet',refPath:'associate_id'})
Outlet.find({}).populate('Associate').exec()
.then(function(alldata){
console.log(alldata)
})
})
合伙人数据库:-
_id: 5b40428088e5f0187dedb342
category_id: 5b34a99709d3ff3e2b5a399c
associate_name: "Cafe Coffee Day"
associate_address: "Coffee day kormangala"
associate_contact: "989545458645"
associate_email: "ccdkor@yahoo.com"
active: true
__v: 0
出口数据库:-
_id: 5b4471f4c5bf8018409c7c64
associate_id: 5b40428088e5f0187dedb342
city_id: 5b3c49fee0de9210a60a2266
outlet_name: "Coffee Day Whitefield"
oulet_address: " Coffee Day Whitefield"
outlet_contact: "7587454478"
active: true
__v:0
预期输出:-
{
"_id": "5b40428088e5f0187dedb342",
"name": "Cafe Coffee Day",
"outlets": [
{
"_id": "5b4471f4c5bf8018409c7c64",
"associate_id": 5b40428088e5f0187dedb342,
"name": "Coffee Day Whitefield",
}]
【问题讨论】:
-
您可以使用
$lookup聚合来填充associates 模型中的outlet -
在使用 $lookup 时,我得到的结果为 "{"_pipeline":[{"$project":{"deal_on":"$deal_on"}},{"$lookup":{" from":"Outlet","localField":"outlet_id","foreignField":"_id","as":"OutletData"}}],"options":{}}"
-
你必须把你的样本集合和输出看看
$lookup是如何工作的 -
我正在尝试使用 associate_id 获取所有出口详细信息和关联详细信息。我怎样才能加入并将所有详细信息放在一起..请参考:以上模式并帮助我。提前致谢。
-
请发布您从 robomongo 或 mongo shell 复制的样本集合,这样我会更容易向您展示
$lookup的工作原理
标签: javascript mongodb mongoose