简体   繁体   中英

Populate many subdocument levels down in mongoose

I'm creating a comment system where a comment can have subComments (when you comment on a comment). I can say how many levels deep I want to populate the subComments, but I don't know how many there are in advance. Is there a way to tell mongoose to just keep populating the subComments of already populated comments until there are no more subDocuments?

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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