如何定义mongoose模式,为其嵌入式文档设置相同的模型和类型。

问题描述 投票:0回答:1

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

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
mongodb mongoose mongoose-schema
1个回答
0
投票

你可以使用 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
© www.soinside.com 2019 - 2024. All rights reserved.