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

>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

Using your presave hooked

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

doc.set("password", "newpassword") // 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


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

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

Leave a ReplyCancel reply