猫鼬:findOneAndUpdate预钩子不起作用 [英] Mongoose: findOneAndUpdate pre hook not working

查看:49
本文介绍了猫鼬:findOneAndUpdate预钩子不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了这个问题,发现的所有解决方案实际上都无效.我目前正在使用此函数在存储在数据库中之前对密码进行加密,但是即使在登录this时更改了值,也不会像在函数中更改过密码那样存储密码.

I've searched about this issue and all the solutions that I've found didn't actually work. I'm currently using this function to encrypt the password before storing in the database but even though the values are being changed when logging this, the password isn't stored like it was changed in the function.

UserSchema.pre('findOneAndUpdate', function(next) {
  const update = this.getUpdate();
  if (!_.isEmpty(update.password)) {
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(update.password, salt, (err, hash) => {
        this.getUpdate().password = hash;
        next();
      })
    })
  }
  next();
});

我也尝试过更改this._update.password的值,但是它也不起作用.我也尝试使用$set或什至使用post钩子,但是它们都没有帮助.我在做什么错了?

I've also tried to change the value of this._update.password instead but it didn't work either. I've also tried using $set or even using a post hook but none of them helped either. What am I doing wrong?

推荐答案

我刚刚在本地进行了以下测试:

I just tested this locally with:

var result = Author.findOneAndUpdate({ _id: <some id> }, { password: '111' }).exec()

和这个pre钩子:

AuthorSchema.pre('findOneAndUpdate', function(next) {
  this._update.password = 'BBB'
  next();
});

密码已另存为BBB

作者模式的密码字段为type: String

Author schema has a password field which is type: String

我在 3.6.5

在您的bcrypt情况下,您还有一个不带else的额外next(),这会使您感到困惑……应该是:

In your bcrypt case you have also an extra next() without else which is messing you up ... should be:

UserSchema.pre('findOneAndUpdate', function(next) {
  const update = this.getUpdate();
  if (!_.isEmpty(update.password)) {
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(update.password, salt, (err, hash) => {
        this.getUpdate().password = hash;
        next();
      })
    })
  } else {
    next();
  }
});

这篇关于猫鼬:findOneAndUpdate预钩子不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆