Home > Enterprise >  How to create a dynamic nested mongoose document with the same schema on multiple levels
How to create a dynamic nested mongoose document with the same schema on multiple levels

Time:07-12

Before everyone tells me I can't call a const before initializing, I do know that. But I think this is the simplest way to render the concept I have in mind, (where any subdocument within the replies array also has the same schema as the parent, and documents within the replies array of those subdocuments also having the same schema). I would really appreciate anyone's input.

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

var commentSchema = new mongoose.Schema({
   content: String,
   createdAt: {
      type: Date,
      default: Date.now
   },
   score: {
      type: Number,
      default: 1
   },
   username: {
      type: String,
      lowercase: true
   },
   parent: { 
      type: Schema.Types.ObjectId,
      ref: 'comment'
   },
   replyingTo: String,
   replies: [commentSchema]
});

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

CodePudding user response:

Since a const can't be called before initialization, to fix this issue the parent schema should be called on the children array after initialization the code below:

commentSchema.add({ replies: [commentSchema] })

The final result should look like this:

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

const commentSchema = new mongoose.Schema({
   content: String,
   createdAt: {
      type: Date,
      default: Date.now
   },
   score: {
      type: Number,
      default: 1
   },
   username: {
      type: String,
      lowercase: true
   },
   parent: { 
      type: Schema.Types.ObjectId,
      ref: 'comment'
   },
   replyingTo: String,
});
commentSchema.add({ replies: [commentSchema] })

  • Related