Quiero convertir mi código existente al marco de agregación de mongoDB. Aquí está mi código que quiero convertir en agregación.
const comments = await Comments.find({post:req.params.id}) .populate({ path:"comments", populate:{ path:"author", select:"name photo" }, select:{ createdAt:1, author:1, _id:1, body:1, likes:1 } }) .populate("author","photo name") .select({ createdAt:1, author:1, _id:1, body:1, comments:1, likes:1 }) .sort("-createdAt");Puede usar la siguiente agregación
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 } } ])