Search code examples
mongodbmongooseaggregation-frameworkmongoose-schema

Querying a parent child referencing in mongoose


I have the comment model as:

const commentSchema = new Schema(
  {
    content: String,
    score: Number,
    replyingTo: { type: mongoose.Types.ObjectId, ref: "Comment" },
  }
);
const Comment = mongoose.model("Comment", commentSchema);

I want to return a query like below. how can I do that?

{
content:"s sample content for comment",
score:12,
replies:["644914e42dcb3e56cf9e8f4b" , "675fd4914e42dcb3edfr8f9e8f4b" ,"234fd4914e42dcb3edfr8dfr8f4b"]
}

I guess with virtual properties or aggregation framework can we do that


Solution

  • you can get the array of replies by doing a self $lookup. After that it is just a $project. Since your output has stringified object ids you might have to $map through the array and convert each $toString. If this is not needed you can just project replies: "$replies._id"

    db.comments.aggregate([
      {
        $lookup: {
          from: "comments",
          localField: "_id",
          foreignField: "replyingTo",
          as: "replies"
        }
      },
      {
        $project: {
          _id: 0,
          content: 1,
          score: 1,
          replies: {
            $map: {
              input: "$replies",
              as: "reply",
              in: {
                $toString: "$$reply._id"
              }
            }
          }
        }
      }
    ])
    

    playground