【发布时间】:2019-06-18 02:37:20
【问题描述】:
我在outsideServices 模型里面有这个:
name: String,
salary: Number,
services: [
{
category: {
ref: 'ServiceCategories',
type: Schema.Types.ObjectId
},
types: [
{
ref: 'ServiceType',
type: Schema.Types.ObjectId
}
]
}
]
我在incidents 模型里面有这个:
outsideServices: {
ref: 'OutsideService',
type: Schema.Types.ObjectId
}
所以当从 api 请求 incidents 时,响应会是这样的:
[
{
category: '5cf655135a1b72106777c238',
types: ['5cf655a85a1b72106777c239']
},
{
category: '5cf656525a1b72106777c23b',
types: ['5cf656835a1b72106777c23c']
}
];
如何查找categories 和types ref 并在我的回复中保留上面的结构?
这是我迄今为止尝试过的,但我无法得到想要的结果:
aggregate.lookup({
from: 'outsideservices',
let: { serviceId: '$outsideServices' },
pipeline: [
{ $match: { $expr: { $eq: ['$_id', '$$serviceId'] } } },
{
$lookup: {
from: 'servicecategories',
let: { services: '$services.category' },
pipeline: [{ $match: { $expr: { $in: ['$_id', '$$services'] } } }],
as: 'category'
}
},
{
$lookup: {
from: 'servicetypes',
let: { services: '$services.types' },
pipeline: [
{ $match: { $expr: { $in: ['$_id', '$$services'] } } }
],
as: 'types'
}
}
],
as: 'outsideService'
});
想要的结果/结果与上面的响应类似,但包含填充文档而不是 ObjectIds
MongoDB版本4.0.10
【问题讨论】: