【问题标题】:Mongoose changes password every time I save with pre-save hook每次我使用预保存挂钩保存时,猫鼬都会更改密码
【发布时间】:2018-01-04 11:10:04
【问题描述】:

我正在使用带有 bcrypt 的预保存挂钩来加密系统上的密码。创建或更改密码时它工作正常。问题是每次我更改并保存不同的字段(例如电子邮件)时,它似乎都会重新加密密码。

用代码可能更容易解释。这是模型:

const UserSchema = new Schema({
    email: {
        type: String,
        required: true,
        lowercase: true,
        unique: true,
        trim: true
    },
    password: {
        type: String,
        required: true
    }
})

还有钩子:

UserSchema.pre('save', function(next){
    const user = this;
    console.log(user);
    bcrypt.genSalt(10, function(err, salt){
        if (err){ return next(err) }

        bcrypt.hash(user.password, salt, null, function(err, hash){
            if(err){return next(err)}

            user.password = hash;
            next();
        })
    })
});

这是我更新电子邮件地址的代码:

module.exports = function(req, res){
    User.findOne({ _id: req.body.user}, function(err, doc){
        if(err){
            console.log(err);
            return;
        }

        doc.email = req.body.data;
        doc.save(function(err, returnData){
            if (err){
                console.log(err);
                return;
            }
            res.send(returnData);
        })

    })
}

因此,当我在最后一个示例中调用doc.save 时,它会按预期更新电子邮件地址,但也会重新加密密码,这意味着如果用户随后注销,他们将无法再次登录。

谁能帮助解决这个问题?

【问题讨论】:

    标签: javascript node.js mongoose mongoose-schema


    【解决方案1】:

    试试这个:

    UserSchema.pre('save', function(next){
        if (!this.isModified('password')) return next();
    
        const user = this;
        
        bcrypt.genSalt(10, function(err, salt){
            if (err){ return next(err) }
    
            bcrypt.hash(user.password, salt, null, function(err, hash){
                if(err){return next(err)}
    
                user.password = hash;
                next();
            })
       })
    });
    

    【讨论】:

    • 哈哈,我只是想通了,并添加了我自己的答案!不过,我已将您的答案标记为正确答案,感谢您抽出宝贵时间!
    • 在声明之前不能使用用户变量。第二行应该是if (!this.isModified('password')) return next();
    【解决方案2】:

    好的,我设法弄明白了——只需要在 pre-save 钩子中添加一点条件逻辑:

    UserSchema.pre('save', function(next){
        if(!this.isModified('password')){
            return next();
        } // Adding this statement solved the problem!!
        const user = this;
        bcrypt.genSalt(10, function(err, salt){
            if (err){ return next(err) }
    
            bcrypt.hash(user.password, salt, null, function(err, hash){
                if(err){return next(err)}
    
                user.password = hash;
                next();
            })
        })
    });
    

    【讨论】:

      猜你喜欢
      • 2017-08-19
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 2012-08-08
      • 2018-07-25
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      相关资源
      最近更新 更多