Node.js 如何将mongoose find查询转换为mongoDB聚合框架?
我想将现有代码转换为mongoDB聚合框架。 这是我要在聚合中转换的代码Node.js 如何将mongoose find查询转换为mongoDB聚合框架?,node.js,mongodb,mongoose,aggregation-framework,Node.js,Mongodb,Mongoose,Aggregation Framework,我想将现有代码转换为mongoDB聚合框架。 这是我要在聚合中转换的代码 const comments=wait comments.find({post:req.params.id}) .填充({ 路径:“评论”, 填充:{ 路径:“作者”, 选择:“姓名照片” }, 选择:{ createdAt:1, 作者:1,, _id:1, 正文:1, 喜欢:1 } }) .填充(“作者”、“照片名”) .选择({ createdAt:1, 作者:1,, _id:1, 正文:1, 评论:1, 喜欢:1
const comments=wait comments.find({post:req.params.id})
.填充({
路径:“评论”,
填充:{
路径:“作者”,
选择:“姓名照片”
},
选择:{
createdAt:1,
作者:1,,
_id:1,
正文:1,
喜欢:1
}
})
.填充(“作者”、“照片名”)
.选择({
createdAt:1,
作者:1,,
_id:1,
正文:1,
评论:1,
喜欢:1
})
.sort(“-createdAt”)代码>您可以使用下面的聚合
Comments.aggregate([
{ "$match": { "post": mongoose.Types.ObjectId(req.params.id) } },
{ "$sort": { "createdAt": -1 } },
{
"$lookup": {
"from": Comment.collection.name,
"let": { "comments": "$comments" },
"pipeline": [
{ "$match": { "$expr": { "$in": ["$_id", "$$comments"] } } },
{
"$lookup": {
"from": Author.collection.name,
"let": { "author": "$author" },
"pipeline": [{ "$match": { "$expr": { "$eq": ["$_id", "$$author"] } } }, { "$project": { "name": 1, "photo": 1 } }],
"as": "author"
}
},
{ "$unwind": "$author" },
{ "$project": { "createdAt": 1, "author": 1, "_id": 1, "body": 1, "likes": 1 } }
],
"as": "comments"
}
},
{
"$lookup": {
"from": Author.collection.name,
"let": { "author": "$author" },
"pipeline": [{ "$match": { "$expr": { "$eq": ["$_id", "$$author"] } } }, { "$project": { "name": 1, "photo": 1 } }],
"as": "author"
}
},
{ "$unwind": "$author" },
{
"$project": {
"createdAt": 1,
"author": 1,
"body": 1,
"comments": 1,
"likes": 1
}
}
])