'How to perform the pre save hook functionality when updating
In my document I have some properties called height, weight, BMI. I used the pre save hook to calculate and store the BMI on document create or save. But I want to Update the BMI whenever the height or weight is updated.
//this is the pre save hook that I used
studentSchema.pre('save', function (next) {
this.bmi = calcBMI(this.height, this.weight);
next();
});
//BMI Calculating Function
exports.calcBMI = (height, weight) => {
const heightInMeters = height / 100;
const bmi = (weight / heightInMeters ** 2).toFixed(2);
return bmi;
};
This function works well when I create a new student.
Solution 1:[1]
you have to use mongoose setters in schema like:
const studentSchema = new Schema({
weight: {
type: Number,
set: () => this.bmi = calcBMI(this.height, this.weight);
},
...same with height
});
official mongoose page: mongoose setters page
Solution 2:[2]
You can use isModified() helper function on a document property and check if it's change or not
studentSchema.pre('save', function (next) {
const std = this;
if(std.isModified("height") || std.isModified("weight")){
this.bmi = calcBMI(this.height, this.weight)
}
next();
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marco Bertelli |
| Solution 2 |
