【发布时间】:2022-02-23 07:22:34
【问题描述】:
我有一个 mongoose Schema 调用用户名,我正在尝试在虚拟中连接用户名。当我在 get 中记录 virtual 或在这些模型中执行函数时,它返回未定义。
我参考了文档,其中示例是嵌套模型,我更喜欢当前模型而不是嵌套它。 我希望任何机构都可以帮助我。
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstname: {
type: String,
lowercase: true,
required: true
},
lastname: {
type: String,
lowercase:true,
text: true,trim: true,
required: true},
middlename: {
type: String,
text: true,trim: true,
lowercase: true
}
UserSchema.virtual('fullname')
.get(function(){
return this.firstname + ' ' + this.lastname;
})
.set(function(firstname, lastname) {
firstname = this.firstname;
lastname = this.lastname;
});
UserSchema.set('toObject', {virtuals: true});
UserSchema.set('toJSON', {virtuals: true});
});
const User = module.exports = mongoose.model('User', UserSchema);
【问题讨论】: