Mongoose 基于另一个字段动态引用填充 [英] Mongoose Populate base on another field Dynamic ref

查看:65
本文介绍了Mongoose 基于另一个字段动态引用填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个架构老师,

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 === Teacher user_id 来自 TeacherSchema

how can I populate CommentSchema on based of user_type ,Eg. if user_type === Teacher user_id isfrom TeacherSchema

推荐答案

在这种情况下,您可以使用 populate 和 动态参考.例如:

In this case, you can use populate with dynamic ref. For example:

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

这篇关于Mongoose 基于另一个字段动态引用填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆