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



我正在创建一个注释系统,其中注释可以有subComments(当您对注释进行注释时(。我可以说我想填充subComments的深度有多少,但我不知道提前有多少。有没有办法告诉猫鼬继续填充已经填充的注释的子注释,直到没有更多的子文档?

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

请检查图形查找功能:https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/

带有数组的示例可以在此处找到:https://www.oodlestechnologies.com/blogs/how-to-use-graphlookup-in-mongodb/

最新更新