我希望我的 pre('save') mongoose 函数只运行一次 [英] I want my pre('save') mongoose function to operate only once

查看:70
本文介绍了我希望我的 pre('save') mongoose 函数只运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I do not know if the exact request in title is possible, but if not; i would really appreciate an alternate solution.

我有这个猫鼬的预存方法

I have this pre save method of mongoose

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

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

When i save new user(owner) a hash is created successfully and all is good>

登录时出现问题.当我登录时,我使用如下 mongoose 自定义方法生成 jwt

The problem occurs when i login. when i login i generate jwt with a mongoose custom method as below

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"中,同时我将新令牌添加到数据库中的记录中.到目前为止一切正常,响应成功返回>

as you see i generate token to send it in "res" and at the same time i add the new token to the record in the data base. all working fine till now and the response is returned successfully>

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

BUT!! while i performed save() in the generate token function to save the token>> the previous pre(save) function ran again, so that a new hash is generated for the password feild.

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

when i try to login again, the password had already changed from calling the pre save hashing function when generating the token in the first login.

是否有解决此问题的解决方法?

Any workaround for solving this issue?

推荐答案

您可以使用 'password' 字段上的 isModified 方法.

我是这样使用的,只有在修改了密码属性时才运行bcrypt:

I use it in this way, only run bcrypt if the password property was changed:

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

这篇关于我希望我的 pre('save') mongoose 函数只运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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