gpt4 book ai didi

javascript - 实例方法在 Sequelize 4 上不起作用

转载 作者:行者123 更新时间:2023-12-02 21:51:11 25 4
gpt4 key购买 nike

有型号代码:

'use strict';
const bcrypt = require('bcrypt');

module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
}, {
hooks: {
beforeCreate: user => {
const salt = bcrypt.genSaltSync();

user.password = bcrypt.hashSync(user.password, salt);
}
},
});

User.prototype.isPasswordValid = password => {
console.log('current_email');
console.log(this.email);
//return bcrypt.compareSync(password, this.password);
};

User.associate = models => {
// associations can be defined here
};

return User;
};

当我执行这段代码时:

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

if (!user || !user.isPasswordValid(password)) {
ctx.body = {
result: RESULT_CODE.ERROR,
error: ERROR_CODE.UNAUTHORIZED,
};

return;
}

我看到以下输出:

current_email
undefined

我不明白为什么我无法访问用户字段。

版本:

    "sequelize": "4.3.1",
"sequelize-cli": "4.0.0"

最佳答案

尝试使用常用函数而不是箭头函数

User.prototype.isPasswordValid = function(password) {
console.log('current_email');
console.log(this.email);
//return bcrypt.compareSync(password, this.password);
};

关于javascript - 实例方法在 Sequelize 4 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60128629/

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