【问题标题】:Mongoose .pre not saving hashed passwords to the DBMongoose .pre 不将散列密码保存到数据库
【发布时间】:2018-03-28 01:41:27
【问题描述】:

使用 Passport 和 mongoose,我正在尝试对保存到数据库的密码进行哈希处理,但它根本没有发生。

我已经定义了模型,并且我可以确认对象正在写入数据库,所以它必须在我的预保存中间件定义的块中。

UserSchema.pre('save', (next) => {
    console.log('Pre-Save Hash has fired.')
    let user = this;
    bcrypt.genSalt(10, (err, salt) => {
        if (err) console.error(err);
        bcrypt.hash(user.password, salt, (err, hash) => {
            user.password = hash;
            next();
        });
    });
});

不知道为什么当我清楚地有东西时它以明文形式保存密码字段。它可能执行不正确。 (中间件中的 console.log 确实会记录到控制台。

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    尝试为您的预保存回调使用常规函数而不是箭头函数,以确保 this 引用正在处理的文档:

    UserSchema.pre('save', function (next) {
      console.log('Pre-Save Hash has fired.')
      let user = this
      bcrypt.genSalt(10, (err, salt) => {
        if (err) console.error(err)
        bcrypt.hash(user.password, salt, (err, hash) => {
          user.password = hash
          next()
        })
      })
    })
    

    【讨论】:

    • 我有同样的问题,我正在使用常规函数。控制台甚至在调用 next() 之前记录了正确的这个对象,并且数据库仍然是明文......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    相关资源
    最近更新 更多