Home > Mobile >  Mongoose isModified, what exactly is it checking?
Mongoose isModified, what exactly is it checking?

Time:08-24

I have seen this exact isModified check or similar a lot upon searching, looked at Mongoose's documentation, and I can't seem to wrap my head around what exactly is its purpose or inclusion.

The first scenario I thought of was perhaps the check is for if the user was trying to reset their password and the check is to see if the "new password" matched the "db password," but that didn't make sense because the password would be stored as a hash. So now I'm at a loss.

schema.pre("save", async function(next) {

  if (!this.isModified("password")) {
    return next();
  }


  try {
    const salt = await bcrypt.genSalt(10);
    let hashedPassword = await bcrypt.hash(this.password, salt);
    this.password = hashedPassword;
    return next();
  } catch (error) {
    return next(error);
  }
});

CodePudding user response:

It detects whether the path changed and returns true/false. As example showed, this works only if you modify the mongoose object using set, it doesn't work when you use UpdateOne or UpdateMany https://mongoosejs.com/docs/api/document.html#document_Document-isModified

Using your presave hooked

let doc = await model.FindOne({})
doc.set("username", "john")
doc.save() // isModified('password') returns false


doc.set("password", "newpassword")
doc.save() // isModified('password') returns true

In your presave hooked, your hook check if you set a new password, and if you did, they hash the password and update the password field with a hash of the new password

e.g.

doc.set("password", "newpassword")
doc.save()

You will find a random hash saved in your password field, and not "newpassword"

  • Related