In order to reuse a pre-middleware function within another pre-middleware, I have extracted a function as shown below:
async function encryptPassword(next) {
if (!this.isModified('password')) {
return next();
}
this.password = await bcrypt.hash(this.password, 5);
this.passwordChangedAt = new Date();
next();
}
UserSchema.pre('save', encryptPassword);
UserSchema.pre("findOneAndUpdate", encryptPassword);
However, an error is occurring stating that the this.isModified
function is not recognized. It appears that this
may be referencing something other than intended. How can this issue be resolved?