我有一个产品模型,它具有以下架构
const product = {
...other fields,
ratings: [
{
star: Number,
postedBy: {
type: ObjectId,
ref: "User",
},
},
],
}
我想在mongoose中填充ratings.postedBy聚合管道
在正常的查找查询中,我会这样做
const product = Product
.find({})
.populate({
path: "ratings.postedBy",
select: "_id name email picture",
});
我会得到这样的查询
"ratings": [
{
"_id": "63fac53330e5bc099651d33c",
"star": 4,
"postedBy": {
"_id": "6241b25f8b01924f5c75cd82",
"name": "Adrian",
"email": "adrianjohn@gmail.com",
"picture": "https://graph.facebook.com/jujialdald19132/picture"
}
},
{
"_id": "63fb22a9d284a9066d97bf1f",
"star": 5,
"postedBy": {
"_id": "6241b32d8b01924f5c75cd85",
"name": "tommy",
"email": "tommy@gmail.com",
"picture": ""
}
}
]
如何在聚合管道中执行完全相同的操作?
这是我曾经尝试过的
const product = await Product.aggregate([
...other pipeline stages
{
//populate ratings.postedBy
$lookup: {
from: "users", //table name
localField: "ratings.postedBy",
foreignField: "_id",
as: "ratings.postedBy",
pipeline: [{ $project: { _id: 1, name: 1, star: 1 } }],
},
},
]);
反过来,我得到查询在这个形状
"ratings": {
"postedBy": [
{
"_id": "6241b25f8b01924f5c75cd82",
"name": "Adrian",
"email": "adrianjohn@gmail.com"
},
{
"_id": "6241b32d8b01924f5c75cd85",
"name": "tommy",
"email": "tommy@gmail.com"
}
]
}
敬请指教。
非常感谢。
1条答案
按热度按时间c0vxltue1#
一个完整的工作示例:
填充结果和聚合结果的日志:
软件包版本: