gpt4 book ai didi

node.js - Mongodb 聚合管道使用 $lookup 从数组返回多个字段

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:10 25 4
gpt4 key购买 nike

我正在尝试从 Post doc 中获取 createAt 排序的评论列表,其中聚合管道将用于使用 displayName 和 profilePhoto 字段填充评论字段中评论的所有者。

帖子架构:

{
_owner: { type: Schema.Types.ObjectId, ref: 'User', required: true },
...
comments: [
{
_owner: { type: Schema.Types.ObjectId, ref: 'User' },
createdAt: Number,
body: { type: String, maxlength: 200 }
}
]
}

用户架构:

{
_id: '123abc'
profilePhoto: String,
displayName: String,
...
}

我想要返回的内容:

[
{
"_id": "5bb5e99e040bf10b884b9653",
"_owner": {
"_id": "5bb51a97fb250722d4f5d5e1",
"profilePhoto": "https://...",
"displayName": "displayname"
},
"createdAt": 1538648478544,
"body": "Another comment"
},
{
"_id": "5bb5e96686f1973274c03880",
"_owner": {
"_id": "5bb51a97fb250722d4f5d5e1",
"profilePhoto": "https://...",
"displayName": "displayname"
},
"createdAt": 1538648422471,
"body": "A new comment"
}
]

我有一些工作代码,首先从聚合开始获取排序的注释,然后单独填充,但我希望能够仅通过使用聚合管道来获取此查询。

当前的解决方案如下所示:

  const postComments = await Post.aggregate([
{ $match: { _id: mongoose.Types.ObjectId(postId) } },
{ $unwind: '$comments' },
{ $limit: 50 },
{ $skip: 50 * page },
{ $sort: { 'comments.createdAt': -1 } },
{$replaceRoot: {newRoot: '$comments'}},
{
$project: {
_owner: 1,
createdAt: 1,
body: 1
}
}
]);

await Post.populate(postComments, {path: 'comments._owner', select: 'profilePhoto displayName' } )

最佳答案

您可以尝试以下聚合

const postComments = await Post.aggregate([
{ "$match": { "_id": mongoose.Types.ObjectId(postId) } },
{ "$unwind": "$comments" },
{ "$lookup": {
"from": "users",
"localField": "comments._owner",
"foreignField": "_id",
"as": "comments._owner"
}},
{ "$unwind": "$comments._owner" },
{ "$replaceRoot": { "newRoot": "$comments" }},
{ "$sort": { "createdAt": -1 } }
{ "$limit": 50 }
])

关于node.js - Mongodb 聚合管道使用 $lookup 从数组返回多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52647768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com