为了清楚起见,让我有两个mongoose
是的schema
模型
let product = new Schema({
name: String,
category: String,
_id: ObjectId,
variants: [{
_id: ObjectId,
attr: String,
attrValue: String
}]
})
let order = new Schema({
_id: ObjectId,
items: [{
product: {
type: ObjectId,
ref: 'Product'
},
variant: {
type: ObjectId,
// ref: 'Product.Variant' // I am sure what it should be
},
quantity: Number
}]
})
对于这些schema
,同时从orders collection
查询
我该如何populate
variant
?
Order.findById(orderId)
.populate('items.product', 'name category')
.populate('items.variant')
我需要类似的东西
{
_id: 'order-id',
items: [
{
product: {
_id: 'product-1',
name: 'product name',
category: 'product category'
},
variant: {
_id: 'variantId',
attr: 'attribute name',
attrValue: 'attribute value'
}
}
]
}
使用populate
是否可以实现?
当前,我必须获取填充的variants
中的所有products
,然后找到variant
并将其手动附加到order.items.variant