I have come across this specific isModified
check frequently while researching, and even after reviewing Mongoose's documentation, I still struggle to grasp its precise purpose or significance.
Initially, I considered the possibility that the check was related to a user resetting their password, with the intention of verifying if the "new password" matched the "db password." However, this theory doesn't hold up because passwords are typically stored as hashes. Now, I find myself unsure of the true reason behind this conditional statement.
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);
}
});