我希望我的 pre('save') 猫鼬函数只运行一次

I want my pre('save') mongoose function to operate only once

我不知道标题中的确切要求是否可行,但如果不行;我真的很感激替代解决方案。

猫鼬有这个预存方法

ownerSchema.pre("save", function(next) {


 const owner = this;
  bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(owner.password, salt, function(err, hash) {
      // Store hash in your password DB.
      owner.password = hash;
      next();
    });
  });
});

当我保存新用户(所有者)时,哈希创建成功,一切正常>

登录时出现问题。当我登录时,我使用猫鼬自定义方法生成 jwt,如下所示

ownerSchema.methods.generateToken = function(cb) {
  var owner = this;
  var token = jwt.sign(
    {
      _id: owner._id,
      username: owner.username,

      email: owner.email,
      category: owner.category === 0 ? false : true,
      phones: owner.phones,
      address: owner.address
    },
    config.SECRET,
    { expiresIn: "1h" }
  );
   owner.token= token;

  owner.save(function(err,owner){
    if(err) return cb(err);
    cb(null,owner);
  })
};

如您所见,我生成令牌以在 "res" 中发送它,同时我将新令牌添加到数据库中的记录中。到目前为止一切正常,响应成功返回>

但是!!当我在生成令牌函数中执行 save() 以保存令牌时 >> 之前的预(保存)函数再次 运行,以便为密码字段生成新的哈希值。

当我尝试再次登录时,密码已经从第一次登录生成令牌时调用预保存散列函数更改。

有解决此问题的解决方法吗?

您可以在 'password' 字段上使用 isModified 方法。

我是这样使用的,只有运行 bcrypt 如果密码属性被更改了:

UserSchema.pre('save', function (next) {
  var user = this;

  if (user.isModified('password')) {
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(user.password, salt, (err, hash) => {
        user.password = hash;
        next();
      });
    });
  } else {
    next();
  }
});