我正在尝试为 Ionic 应用程序实现基于 MongoDB 和 NestJS 的身份验证,并在向路由api/users发出 POST 请求后收到以下错误消息:
[Nest] 85372 - 2020 年 3 月 26 日,14:04:49 [ExceptionsHandler] 无法读取未定义的属性“密码”+23790ms
在我的 users.schema.ts 文件中获取错误消息:
'this' 到局部变量的意外别名。eslint(@typescript-eslint/no-this-alias)
我的 users.schema.ts 看起来像这样(注释错误的行):
import * as mongoose from 'mongoose';
import * as bcrypt from 'bcryptjs'
export const UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
unique: true,
required: true
},
createdAt: {
type: Date,
default: Date.now
},
updatedAt: {
type: Date,
default: Date.now
}
});
UserSchema.pre('save', function (next) {
const user = this; // This is marked as an error in vs code
if (!user.isModified('password')) return next();
bcrypt.genSalt(10, (err, salt) => {
if (err) return next(err);
bcrypt.hash(this.user.password, salt, (err, hash) => {
if (err) return next();
this.user.password = hash;
next();
});
});
});
UserSchema.methods.checkPassword = (attempt, callback) => {
bcrypt.compare(attempt, this.user.password, (err, isMatch) => {
if (err) return callback(err);
callback(null, isMatch);
})
}
我尝试使用箭头函数实现相同的模式,但是在向api/users发出 POST 请求后收到以下错误消息:
[Nest] 85947 - 2020 年 3 月 26 日,14:09:30 [ExceptionsHandler] 无法读取未定义的属性“isModified”+22567ms
UserSchema.pre('save', (next) => {
if (!this.user.isModified('password')) return next();
bcrypt.genSalt(10, (err, salt) => {
if (err) return next(err);
bcrypt.hash(this.user.password, salt, (err, hash) => {
if (err) return next();
this.user.password = hash;
next();
});
});
});
我在这里做错了什么?