Im trying to calculate a users BMI and send it through to my MongoDB atlas db, the bmi will be calculated through the height and weight that users enter, I've set up a Mongoose Schema that set out the function but at this point my bmi is not showing on the post request, can anyone steer me in the right direction?
const mongoose = require('mongoose');
const users = mongoose.Schema({
username:{
type: String,
required: true
},
first:{
type: String,
required: true
},
last:{
type: String,
required: true
},
occupation:String,
profile:{
age:{
type: Number,
required: true
},
sex:{
type: String,
required: true
},
height:{
type: Number,
required: true
},
weight:{
type: Number,
required: true
},
//Issue is here. Trying to use the Schema to 'pre' calculate
bmi:{
type: Number,
get: () =>{
let BMI = weight/height ** 2
return BMI
},
set: BMI => BMI,
alias: 'bmi',
},
eyeColor: String,
incomePM: Number,
interestedIn: String
}
})
module.exports = mongoose.model('users', users);
CodePudding user response:
Try using the pre
middleware of mongoose,
const mongoose = require('mongoose');
const users = mongoose.Schema({
username:{
type: String,
required: true
},
first:{
type: String,
required: true
},
last:{
type: String,
required: true
},
occupation:String,
profile:{
age:{
type: Number,
required: true
},
sex:{
type: String,
required: true
},
height:{
type: Number,
required: true
},
weight:{
type: Number,
required: true
},
bmi:{
type: Number,
},
eyeColor: String,
incomePM: Number,
interestedIn: String
}
})
users
.pre('save', function(next){
console.log(this.profile.weight);
console.log(this.profile.height);
this.profile.bmi =
(this.profile.weight/this.profile.height) ** 2;
next();
});
module.exports = mongoose.model('users', users);