【问题标题】:I want my pre('save') mongoose function to operate only once我希望我的 pre('save') mongoose 函数只运行一次
【发布时间】:2020-07-02 18:19:26
【问题描述】:

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

我有这种猫鼬的预存方法

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();
    });
  });
});

当我保存新用户(所有者)时,已成功创建哈希并且一切都很好>

登录时出现问题。当我登录时,我使用如下 mongoose 自定义方法生成 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() 以保存令牌>>之前的 pre(save) 函数再次运行,以便为密码字段生成一个新的哈希。

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

有什么办法可以解决这个问题?

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema mern


    【解决方案1】:

    您可以在“密码”字段中使用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();
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-25
      • 2020-12-19
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多