我正在使用带有Typescript的Node和Mongoose构建后端。我正在尝试实现比较密码方法,但是我得到了this.password(应引用UsersSchema)未定义。
我的模特:
const UserSchema: mongoose.Schema = new mongoose.Schema({
email: {
type: String,
lowercase: true,
validate: {
validator: async function(email) {
const user = await this.constructor.findOne({ email });
if (user) {
if (this.id === user.id) {
return true;
}
return false;
}
return true;
},
message: _props => 'The specified email address is already in use.',
},
required: [true, 'User email required'],
},
password: { type: String, required: true },
role: { type: String, required: true },
});
UserSchema.methods.comparePassword = function(password: string): boolean {
console.log(this.password, 'this.passwor'); //THIS IS UNDEFINED
if (bcrypt.compareSync(password, this.password)) return true;
return false;
};
在我的控制器中
export const login = async (
req: express.Request,
res: express.Response,
_next: express.NextFunction,
) => {
if (req.body.email && req.body.password) {
const { email, password } = req.body;
const user = await UserSchema.findOne({ email });
// Respond with token
if (user) {
const testCompare = user.schema.methods.comparePassword(password);
console.log(testCompare, 'sskskks');
}
}
}
comparePassword
方法被正确调用,但是this.password保持未定义状态。我已经尝试使用bcrypt.compare
代替compareSync
,在控制器中使用回调代替async / await,但是没有任何效果!
我发现其他人也有类似的问题,但似乎没有一个答案可以解决。
编辑****
好吧,我挖了以后找到了答案。我改用bcrypt.compare
,并在函数声明之前绑定this关键字以使其起作用。
UserSchema.methods.isCorrectPassword = function(password, callback) {
const doc = this;
bcrypt.compare(password, doc.password, function(err, same) {
if (err) {
callback(err);
} else {
callback(err, same);
}
});
};