如何定义猫鼬模式以将相同的模型设置为其嵌入式文档的类型

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

假设我正在创建一个名为 'Comment' 的模型,但评论模型的回复字段应为 'Comment' 类型。可能吗?如果是这样帮助我

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

您可以使用this自参考。

 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