Mongoose基于另一个字段Dynamic ref进行填充



我有两个模式老师,

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

在这种情况下,您可以使用带有动态引用的populate。例如:

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

最新更新