繁体   English   中英

在 mongoose 中向下填充许多子文档级别

[英]Populate many subdocument levels down in mongoose

我正在创建一个评论系统,其中评论可以包含子评论(当您对评论发表评论时)。 我可以说我想填充 subComments 的深度,但我不知道预先有多少。 有没有办法告诉 mongoose 继续填充已经填充的评论的子评论,直到没有更多的子文档?

CommentModel.js

const mongoose = require("mongoose");
const schema = mongoose.Schema;

const commentSchema = new schema(
  {
    post: { type: schema.Types.ObjectId, required: true, ref: "post" },
    content: { type: String, required: true },
    votes: { type: Number, required: true },
    user: { type: schema.Types.ObjectId, required: true, ref: "user" },
    subComments: [{ type: schema.Types.ObjectId, ref: "comment" }],
    parentComment: { type: schema.Types.ObjectId, ref: "comment" },
  },
  { timestamps: true }
);

module.exports = Comment = mongoose.model("comment", commentSchema);

PostRouter.js

router.get("/full/:postId", async (req, res) => {
  const postId = req.params.postId;

  const post = await Post.findById(postId).populate({
    path: "comments",
    populate: {
      path: "subComments",
    },
    // how can i populate infinitely down in the path subComments?
  });

  res.json(post);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM