Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongoose isModified, what exactly is it checking?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading