gpt4 book ai didi

javascript - Sequelize : user. checkPassword 不是函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:44 27 4
gpt4 key购买 nike

我正在尝试在sequelize模型中创建一个原型(prototype)函数,以验证我的密码:

const bcrypt = require('bcryptjs');

module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
'User',
{
name: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.VIRTUAL,
password_hash: DataTypes.STRING
},
{
hooks: {
beforeSave: async user => {
if (user.password) {
user.password_hash = await bcrypt.hash(user.password, 8);
}
}
}
}
);

**User.prototype.checkPassword = function(password) {
debugger
return bcrypt.compare(password, this.password_hash);
};**

return User;
};

但是当我将此模型导出到 Controller 并尝试调用 user.checkpassword 时,它给出了 TypeError: user.checkPassword is not a function:

const { User } = require('../models');

class SessionController {
async store(req, res) {
const { email, password } = req.body;
const user = User.findOne({ where: { email } });

if (!user) {
return res.status(401).json({ message: 'User not found' });
}

**if (!(await user.checkPassword(password))) {
return res.status(401).json({ message: 'Incorret password' });
}**

return res.status(200).send();
}
}

module.exports = new SessionController();

这会是什么?

我的 Sequelize 版本是“sequelize”:“^5.21.5”

最佳答案

User.findOne({ where: { email } });

返回一个 promise 。你可能打算这样做

const user = await User.findOne({ where: { email } });

而不是

const user = User.findOne({ where: { email } });

关于javascript - Sequelize : user. checkPassword 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60456153/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com