I have mongoose-schema called UserSchema, which stores information about all users. I want to enable the user to change his information, which I try by using .findByIdAndUpdate. This is the relevant code:
router.post("/updateprofile", function(req,res,next) {
const {id, org, tel, email, firstName, lastName} = req.body;
Users.findByIdAndUpdate(id, {org : org, tel : tel, email : email, firstName : firstName , lastName : lastName}, function (err, response) {
if (err) throw err
res.json(response);
});
});
However, when trying to change the info, I get the following error-message: Cannot read property 'password' of undefined
. I'm pretty sure this is caused by a pre-update hook, but I can not remove it because I need it for my "forgot-password"-functionality.
Here's the code:
UserSchema.pre('findOneAndUpdate', function (next) {
this.update({},{ $set: { password:
bcrypt.hashSync(this.getUpdate().$set.password, 10)}} )
next();
});
I'm confused by why it used that prehook anyway, since in the hook it's looking for findOneandUpdate
and when I try to change the data I'm using findByIdAndUpdate
.
I tried using .update()
instead but that doesn't work either. Does anyone know what I'm doing wrong and how to fix it?