![](/img/trans.png)
[英]MongoDB Aggregate $lookup on array of object with additional field
[英]Aggregate lookup for an object which is part of an array
我正在尝试使用下面的代码通过从 collection companies.contacts
获取数据来填充联系人字段。
// COMPANY MODEL
const objectContact = {
name: { type: String, required: true },
email: { type: String, required: true }
};
const schemaCompany = new mongoose.Schema({
name: { type: String, required: true },
contacts: { type: [objectContact], default: undefined }
});
// -----------------
// ORDER MODEL
const objectOrderTab = {
contact: { type: mongoose.Schema.Types.ObjectId, ref: 'Company' },
};
const schemaOrder = new mongoose.Schema({
orderNo: Number,
orderDate: { type: Date, default: Date.now },
company: { type: mongoose.Schema.Types.ObjectId, ref: 'Company', required: true },
custRFQ: objectOrderTab,
custQUO: objectOrderTab,
});
// -----------------
exports.getOrder = catchAsync(async (req, res, next) => {
let order = await Order.aggregate([
{ $match: { orderNo: parseInt(req.params.order) } },
{ $lookup: { from: 'companies', localField: 'company', foreignField: '_id', as: 'company' } },
{ $lookup: { from: 'companies.contacts', localField: 'custRFQ.contact', foreignField: '_id', as: 'custRFQ.contact' } },
{ $lookup: { from: 'companies.contacts', localField: 'custQUO.contact', foreignField: '_id', as: 'custQUO.contact' } }
]);
res.status(200).json(order);
};
通过使用上面的代码,我可以获得填充公司,但我无法填充custRFQ.contact
和custQUO.contact
。
请帮我一些建议。 提前致谢!
更新:
回应是:
[
{
"_id": "5ff2fb1e6c8567171031c1a4",
"orderNo": 1000,
"company": [
{
"_id": "5fd2bdfa57c6291fe0f0628f",
"name": "DELPHI",
"contacts": [
{
"_id": "5fd2c81175a80e3b54f191c5",
"name": "Some name",
"email": "xxx@delphi.com",
}
]
}
},
"custRFQ": {
"contact": [],
},
"custQUO": {
"contact": [],
}
}
]
指定顺序下定义的联系人存在。 现在我意识到,可能我还需要匹配正在查找的公司。
您在new
objectOrderTab = mongoose.Schema({
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.