【发布时间】:2020-07-07 03:15:59
【问题描述】:
我正在尝试为 Ionic 应用程序实现基于 MongoDB 和 NestJS 的身份验证,并在向路由 api/users 发出 POST 请求后收到以下错误消息:
[Nest] 85372 - 03/26/2020, 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 - 03/26/2020, 14:09:30 [ExceptionsHandler] 无法读取未定义 +22567ms 的属性“isModified”
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();
});
});
});
我在这里做错了什么?
【问题讨论】:
标签: mongodb typescript ionic-framework mongoose bcrypt