Diego Perdomo
Diego Perdomo

Reputation: 463

Mongoose isModified and isNew

I have seen this example in different tutorials and I just wonder why this works with new documents. Are new documents considered modified? Shouldn't we use this.isNew || this.isModified instead of just isModified?

  try {
      if (!this.isModified("password")) {
        return next();
      }
      let hashedPassword = await bcrypt.hash(this.password, 10);
      this.password = hashedPassword;
      return next();
  } catch (err) {
      return next(err);
 }
});

Upvotes: 4

Views: 2057

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17858

The documentation about this is not very clear, so let's learn this by trying:

schema.pre("save", async function(next) {
  console.log("password isModified: ", this.isModified("password"));
  console.log("isNew: ", this.isNew);
  next();
});

When we create a new user, the output will be like this:

password isModified:  true
isNew:  true

So we see the this.isModified("password") is true. So we can understand that this.isModified("password") is also true for new documents.

Upvotes: 3

Related Questions