Mongodb Mongoose基于另一个字段动态引用进行填充
我有两位老师Mongodb Mongoose基于另一个字段动态引用进行填充,mongodb,mongoose,mongoose-schema,mongoose-populate,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,
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\u type
填充CommentSchema
,例如如果user\u type===Teacher
user\u id是fromTeacherSchema
在这种情况下,您可以使用populatewith。例如:
const CommentSchema = mongoose.Schema({
description: String,
user_type: String // Student or Teacher
user_id: {
type: Schema.Types.ObjectId,
refPath: 'user_type'
}
})