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

半城伤御伤魂 提交于 2021-02-05 10:29:28

问题


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>

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

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>

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?


回答1:


You could use isModified method on your 'password' field.

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


来源:https://stackoverflow.com/questions/60794031/i-want-my-presave-mongoose-function-to-operate-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!