Search code examples
mongodbmongoosemongoose-schema

How to define mongoose schema for setting the same model as type for its embedded document


Say I am creating a model called 'Comment' but the reply field of the comment model should be of type 'Comment'. Is it possible? If so help me

const commentSchema = new mongoose.Schema({
  comment: {
    type: String,
    required: true
  },
  author: {
    type: mongoose.Schema.Types.ObjectId,
    required: true
  },
  reply: {
    type: [Comments]
  }
},
  {
    timestamps: true
  })

const Comments = mongoose.model('Comment', commentSchema)
module.exports = Comments

Solution

  • You can use this to self reference.

     const commentSchema = new mongoose.Schema({
      comment: {
        type: String,
        required: true
      },
      author: {
        type: mongoose.Schema.Types.ObjectId,
        required: true
      },
      reply: {
        type: [this]
      }
    },
      {
        timestamps: true
      })
    
    const Comments = mongoose.model('Comment', commentSchema)
    module.exports = Comments