我正在尝试将.pre、.method和.static函数应用于我的Mongoose模式。
我有以下代码,但是我的this要么在错误的上下文中,要么我误解了模式。
export interface IUser extends mongoose.Document {
email: string;
password: string;
firstName: string;
lastName: string;
comparePassword(password: string, callback: Function): void;
}
class UserSchema {
static get schema(): mongoose.Schema {
let userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
lowercase: true
},
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
password: {
type: String,
select: false
}
});
userSchema.pre('save', this.saveHandler);
userSchema.method('comparePassword', this.comparePassword);
return userSchema;
}
static saveHandler(next) {
let user = this.schema;
if(!user.isModified('password')) {
return next();
}
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(user.password, salt, (err, hash) => {
user.password = hash;
next();
});
});
}
static comparePassword(password: string, callback: Function) {
let user = this.schema;
bcrypt.compare(password, user.password, (err, isMatch) => {
callback(err, isMatch);
});
}
}
export const UserModel = mongoose.model<IUser>('User', UserSchema.schema);Typescript抛出错误,Property 'isModified' does not exist on type 'Schema'.
然而,在javascript中:
var schema = new Schema({
email: { type: String, unique: true, lowercase: true },
password: { type: String, select: false },
firstName: String,
lastName: String,
});
schema.pre('save', function(next) {
var user = this;
if(!user.isModified('password')) {
return next();
}
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
user.password = hash;
next();
});
});
});具有正确的this上下文。我如何正确地构造我的Typescript代码才能达到同样的效果呢?
发布于 2021-03-05 17:26:46
使用不带箭头函数的函数工作起来就像Fedoranimus所说的那样
https://stackoverflow.com/questions/38554466
复制相似问题