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);
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With