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.
CodePudding user response:
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
CodePudding user response:
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();
});