I want to implement a parent/child (Self Referencing) relationship for comments with its replies, Here's the code for the schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const BlogCommentSchema = new Schema({
body: String,
dateTime: { type: Date, default: Date.now },
replies: [this]
});
const BlogComment = mongoose.model("blogComments", BlogCommentSchema);
module.exports = BlogComment;
What is the simplest way to get the number of comments or replies of a comment?
Any help would be appreciated.
Clarification: Here's an example of saved a document based on the schema:
{
"replies": [
{
"replies": [
{
"replies": [],
"_id": "5e558aa01f804205102b4a78",
"body": "Comment 1.1.1",
"dateTime": "2020-02-25T20:59:12.056Z"
}
],
"_id": "5e558aa01f804205102b4a79",
"body": "Comment 1.1",
"dateTime": "2020-02-25T20:59:12.057Z"
},
{
"replies": [
{
"replies": [
{
"replies": [
{
"replies": [
{
"replies": [],
"_id": "5e558aa01f804205102b4a7a",
"body": "Comment 1.2.1.1.1",
"dateTime": "2020-02-25T20:59:12.057Z"
}
],
"_id": "5e558aa01f804205102b4a7b",
"body": "Comment 1.2.1.1.1",
"dateTime": "2020-02-25T20:59:12.057Z"
}
],
"_id": "5e558aa01f804205102b4a7c",
"body": "Comment 1.2.1.1",
"dateTime": "2020-02-25T20:59:12.057Z"
}
],
"_id": "5e558aa01f804205102b4a7d",
"body": "Comment 1.2.1",
"dateTime": "2020-02-25T20:59:12.058Z"
}
],
"_id": "5e558aa01f804205102b4a7e",
"body": "Comment 1.2",
"dateTime": "2020-02-25T20:59:12.058Z"
}
],
"_id": "5e558aa01f804205102b4a7f",
"body": "Comment 1",
"dateTime": "2020-02-25T20:59:12.058Z",
"__v": 0
}
I need to get these numbers (total number of replies is 7, number of Comment 1.1
is 1, ...):
Comment 1 (count is 7)
- Comment 1.1 (count 1)
- Comment 1.1.1
- Comment 1.2 (count 4)
- Comment 1.2.1
- Comment 1.2.1.1
- Comment 1.2.1.1.1
- Comment 1.2.1.1.1.1