You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用bcryptjs在Node.js中加密密码失败问题求助

解决bcryptjs加密密码失效问题

你的代码核心问题是pre('save')钩子使用了箭头函数,箭头函数的this不会绑定到Mongoose的文档实例,导致无法修改password和saltSecret字段,最终密码以明文存入数据库。

修正后的代码

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: `Name can't be empty`
  },
  username: {
    type: String,
    required: `Username can't be empty`
  },
  email: {
    type: String,
    required: `Email can't be empty`,
    unique: true
  },
  password: {
    type: String,
    required: `Password can't be empty`,
    minLength: [6, 'Password must be at least 6 character long']
  },
  saltSecret: String
});

// 将箭头函数改为普通函数,确保this指向文档实例
userSchema.pre('save', function(next) {
  bcrypt.genSalt(10, (err, salt) => {
    if (err) return next(err);
    bcrypt.hash(this.password, salt, (err, hash) => {
      if (err) return next(err);
      this.password = hash;
      this.saltSecret = salt;
      next();
    });
  });
});

额外检查项

  • 确保已安装bcryptjs:执行npm install bcryptjs,并在文件顶部引入const bcrypt = require('bcryptjs');
  • 保存用户时必须调用user.save()或User.create(),pre('save')钩子不会在updateOne、findOneAndUpdate等更新方法中触发,若用这类方法修改密码,需手动处理加密逻辑
  • 检查是否有其他代码逻辑覆盖了password字段的原始值

内容的提问来源于stack exchange,提问作者Saap Lal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:39:19