mongodb 在mongoose中查询父/子引用

e4eetjau  于 2023-04-29  发布在  Go
关注(0)|答案(1)|浏览(170)

我的评论模型为:

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

我想返回一个类似于下面的查询。我该怎么做?

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

我想通过虚拟属性或聚合框架我们可以做到这一点

cig3rfwq

cig3rfwq1#

你可以通过执行self $lookup来获得回复数组。在此之后,它只是一个$project。由于您的输出具有字符串化的对象ID,因此您可能需要通过数组$map并转换每个$toString。如果不需要,您可以仅投影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

相关问题