Search code examples
node.jsmongodbmongoosepassport.js

Hashing password before update a user in mongoose


I create the user, hash his password and save on mongo. My problem begins when I try to update that user. For now, when I update the hash isn't generated, cause I really don't know how to do it.

The middleware to get the user that I'm talking about:

exports.userByID = function(req, res, next, id) {
  User.findOne(
    {
      _id: id
    },
    function(err, user) {
      if (err) {
        return next(err);
      } else {
        req.user = user;
        next();
      }
    }
  );
};

The user controller, to update an user:

exports.update = async function(req, res, next) {

  User.findByIdAndUpdate(req.user.id, req.body, function(err, user) {
    if (err) {
      return next(err);
    } else {
      res.json(user);
    }
  });
};

The pre 'save' on User's model:

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

  var user = this;

  if (user.password) {

    var md5 = crypto.createHash("md5");
    user.password = md5.update(user.password).digest("hex");
    console.log("Password após o save (hasheando):" + user.password);
  }

  next();
});

I'm using passport authentication ('local'). Already tried user.save() on the controller update:

user.save();
res.json(user);

But, without success.


Solution

  • This is may be because you are not storing the new_password in the mongo.

    In update controller you have to do like this:

    User.findByIdAndUpdate(req.user.id, req.body, function (err, user) {
      if (err) {
        return next(err);
      } else {
        user.password = req.body.new_password;
        user.save(function (err, user) {
          if (err) {
            res.send("Error: ", err);
          } else {
            res.send("password updated successfully!");
          }
        })
      }
    });