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

问题描述

我有两个架构教师,

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

解决方法

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...