聚合查找作为数组一部分的对象
Posted
技术标签:
【中文标题】聚合查找作为数组一部分的对象【英文标题】:Aggregate lookup for an object which is part of an array 【发布时间】:2021-08-23 14:55:03 【问题描述】:我正在尝试使用下面的代码通过从集合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": [],
]
在指定顺序下定义的联系人存在。 现在我意识到我可能还需要匹配正在查找的公司。
【问题讨论】:
【参考方案1】:您在objectOrderTab = mongoose.Schema(
忘记了new
关键字
【讨论】:
不是这样的。事实上,我会将该子模式转换为普通对象。和我对objectContact
所做的一样。像这样:const objectOrderTab = contact: type: mongoose.Schema.Types.ObjectId, ref: 'Company'
以上是关于聚合查找作为数组一部分的对象的主要内容,如果未能解决你的问题,请参考以下文章