【问题标题】:schema method this keyword is not working架构方法此关键字不起作用
【发布时间】:2021-02-10 07:57:53
【问题描述】:

所以我试图有一个架构函数,它使用哈希版本验证密码,但 this 关键字不起作用

userSchema.methods.validPassword = (pwd)=>{
  const userPwd = this.password;
  console.log(userPwd+' '+pwd);
  const pass = bcrypt.compareSync(pwd, userPwd);
  return pass;
}; 

userPwd 返回 undefined ? 我的解决方法是 -

userSchema.methods.validPassword = (user,pwd)=>{
  const userPwd = user.password;
  console.log(userPwd+' '+pwd);
  const pass = bcrypt.compareSync(pwd, userPwd);
  return pass;
};

这就是我使用该方法的方式-

if(result.validPassword(result,req.body.password)){
          res.redirect('/imgs')
        }else{
          console.log('User password incorrect');
          res.send('G u got da pass wrong')
        }

但我想知道为什么这不起作用。 任何帮助将不胜感激

【问题讨论】:

  • 你能说明你是怎么称呼它的吗?

标签: node.js mongoose mongoose-schema


【解决方案1】:
userSchema.methods.matchPassword = async function (enteredPassword) {
    return await bcrypt.compare(enteredPassword, this.password);
};

您为什么使用 compareSync?

在服务器上的用户控制器中使用的示例...

// @desc    Auth user & get token
// @route   POST /api/users/login
// @access  Public
const authUser = asyncHandler(async (req, res) => {
    const { email, password } = req.body;

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

    if (user && (await user.matchPassword(password))) {
        res.json({
            _id: user._id,
            name: user.name,
            email: user.email,
            isAdmin: user.isAdmin,
            token: generateToken(user._id),
        });
    } else {
        res.status(401);
        throw new Error("Invalid email or password");
    }
});

【讨论】:

    猜你喜欢
    • 2020-09-14
    • 1970-01-01
    • 2023-01-22
    • 2015-11-18
    • 2019-11-14
    • 2012-07-03
    • 2014-10-24
    • 1970-01-01
    • 2020-07-12
    相关资源
    最近更新 更多