猫鼬基于另一个字段填充动态参考

时间:2020-11-12 18:59:02

标签: mongodb mongoose mongoose-schema mongoose-populate

我有两个架构教师,

const TeacherSchema = mongoose.Schema(
  {
    name:String
    _id: ObjectId
})

学生

const StudentSchema = mongoose.Schema(
  {
    name:String
    _id: ObjectId
})

我有评论模式

const CommentSchema = mongoose.Schema(
  {
    description: String,
    user_type:String  // Student or Teacher
    user_id: ObjectId
})

如何基于CommentSchema填充user_type,例如。 if user_type === Teacher user_id来自TeacherSchema

1 个答案:

答案 0 :(得分:1)

在这种情况下,可以使用dynamic ref填充。例如:

const CommentSchema = mongoose.Schema({
  description: String,
  user_type: String  // Student or Teacher
  user_id: {
    type: Schema.Types.ObjectId,
    refPath: 'user_type'
  }
})