I have created a method on my mongoose model like so -
PatientSchema.methods.calculateAge = function(){
let ageDifferenceInMs = (Date.now() - this.dateOfBirth.getTime());
let ageDate = new Date(ageDifferenceInMs);
let age = Math.abs(ageDate.getUTCFullYear() - 1970);
return age;
}
It works perfectly when I retrieve a single instance of the related model. However, my question is how can I add a new key-value pair in a JS object where the value is generated using a method defined in the model when retrieving multiple instances like this -
const patientList = await Patient.find({})
I could do it using a loop, but I'm wondering if there's a more optimized way to achieve this.
UPDATE - As suggested by @Milad Raeisi, I implemented virtuals like this-
PatientSchema.virtual('age').get(function () {
let temp = new Date(this.dateOfBirth)
let ageDifferenceInMs = (Date.now() - temp.getTime());
let ageDate = new Date(ageDifferenceInMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
})
Don't forget to include
mongoose.set('toJSON', { virtuals: true });
Although this works perfectly for a single instance, it returns null for multiple instances.
This is the code snippet I used to get the patient list -
const patientList = await Patient.find({})
.sort({name:1})
.limit(limit)
.skip(skipIndex)
.select(['name', 'gender', 'age'])
.exec();