【问题标题】:Mongoose Populate base on another field Dynamic refMongoose 基于另一个字段填充动态参考
【发布时间】:2021-02-24 19:46:34
【问题描述】:

我有两个schema Teacher,

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
})

如何根据user_type 填充CommentSchema,例如。 if user_type === Teacheruser_id 来自TeacherSchema

【问题讨论】:

    标签: mongodb mongoose mongoose-schema mongoose-populate


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-09-06
      • 1970-01-01
      • 2012-11-24
      • 2013-06-25
      • 2015-05-21
      • 2015-03-04
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多