【发布时间】:2021-04-03 18:12:15
【问题描述】:
我在模型UserSchema中有以下方法:
userSchema.virtual('password')
.set(function(password) {
this._password = password;
this.salt = this.makeSalt();
this.hashed_password = this.encryptPassword(password);
})
.get(function() {
return this._password;
}
);
但是当我创建新的teacher 时出现错误hashed_password is required。所以我认为userSchema 中的virtual 方法不是teacherSchema 中的继承。如何从userSchema 设置teacherSchema 继承方法,如virtual?
型号
const mongoose = require('mongoose');
extend = require('mongoose-extend-schema');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {
type: String,
trim: true,
required: true,
maxLength: 32
},
surname: {
type: String,
trim: true,
required: true,
maxLength: 32
},
email: {
type: String,
unique: true,
trim: true,
required: true,
lowercase: true
},
hashed_password: {
type: String,
required: true
},
initials: String
});
userSchema.virtual('password')
.set(function(password) {
this._password = password;
this.salt = this.makeSalt();
this.hashed_password = this.encryptPassword(password);
})
.get(function() {
return this._password;
}
);
const studentSchema = extend(userSchema, {
teachers: []
});
const teacherSchema = extend(userSchema, {
isActiveTutor: {
type: Boolean,
default: false
}
})
const User = mongoose.model('User', userSchema);
const Student = mongoose.model('Student', studentSchema);
const Teacher = mongoose.model('Teacher', teacherSchema);
module.exports = {
User,
Student,
Teacher
}
【问题讨论】:
标签: javascript node.js mongodb mongoose mongoose-schema