Mongoose aggregate into a nested doc Get count and append new value to the query result Mongoose aggregate into a nested doc Get count and append new value to the query result mongoose mongoose

Mongoose aggregate into a nested doc Get count and append new value to the query result


According to your first expected result, this is a solution

const result = await PostModel.aggregate([{      $project: {          _id: 1,          body: 1,          liked: { $in: [ID(uid), "$likes"] },          likesCount: { $size: "$likes" },          comments: {                _id: 1,                body:1,                liked: { $in: [ID(uid), "$comment.likes"] },                likesCount: { $size: "$comment.location.likes" },                     }}]);

by this query, you will get response like this -

{"_id" : "1234","body" : " hello ! I love mongodb, but its hard","liked" : true,"likesCount" : 1"comments" : {    "_id" : 3453",    "body" : "me I don't like mongodb i like sql ",    "liked" : true,    "likesCount" : 1    "replies" : {        "_id" : "2345",        "body" : "both of them are great",        "liked" : true,        "likesCount" : 1    },}}

And if you want second expected result then this is a solution -

const result = await PostModel.aggregate([{      $project: {          _id: 1,          body: 1,          liked: { $in: [ID(uid), "$likes"] },          likesCount: { $size: "$likes" },          comments: {                _id: 1,                body:1,                liked: { $in: [ID(uid), "$likes"] },                likesCount: { $size: "$likes" },              }      }}])

And expected result by this -

{"_id" : "1234","body" : " hello ! I love mongodb, but its hard","liked" : true,"likesCount" : 1"comments" : {    "_id" : "3453",    "body" : "me I don't like mongodb i like sql ",    "liked" : true,    "likesCount" : 1}}