我可以在猫鼬模式中添加虚拟获取器和设置器。但是,当我要在填充架构时访问它们时,getter将不存在。
我有学生班,学生有他们的名字和名字。 displayName属性定义为虚拟吸气剂,以显示“名字”。 当我直接访问学生模型时,此方法有效。但是当我访问一个班级时,填充的是学生,displayName丢失了。
const studentSchema = new Schema({
name: {type: String, required: true },
prename: {type: String, required: true }
});
studentSchema.virtual('displayName').get(function () {
return this.prename + ' ' + this.name;
});
studentSchema.set('toObject', { virtuals: true });
studentSchema.set('toJSON', { virtuals: true });
const studentModel = mongoose.model('student', studentSchema);
//studentModel.find(...) returns objects with displayName
const classSchema = new Schema({
name: {type: String, required: true },
students: [{ type: Schema.Types.ObjectId, required: true, ref: 'student' }]
});
const classModel = mongoose.model('class', classSchema);
// classModel.find(...).populate('students')... returns class with students, but students don't have a displayName
在班级中填充时,如何将displayName添加到学生数组中? https://mongoosejs.com/docs/api.html#virtualtype_VirtualType-get