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);
});
Please check the graph lookup feature: https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/
Example with arrays can be found here: https://www.oodlestechnologies.com/blogs/how-to-use-graphlookup-in-mongodb/
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.