Search code examples
node.jsmongodbmongoosemongoose-schema

Calculation of third field based on two other field in Mongoose


I have 2 fields on on Mongoose model: totalAttempts and totalRight. I am planning to calculate accuracy based on them.

totalAttempts: {
    type: Number,
    default: 1
},
totalRight: { 
    type: Number,
    default: 1
}

This is what I have done [it doesn't work]

 accuracy:{
     type:Number,
     required:function() {return (this.totalRight/this.totalAttempts*100).toFixed(2)}
}

Also, if I don't put default value on Accuracy I get an error:

ERROR; While creating new question ..ValidationError: Path `accuracy` is require                      d.

events.js:163

What will be the right way to accomplish this ? I already have a working solution to get totalAttempts and totalRight every time user request that Model. But I want to save that calculation and store info on my database.


Solution

  • Pre save is the right way to go. Add it to your schema.

    ModelSchema
    .pre('save', function(next){
      this.accuracy = this.totalRight/this.totalAttempts*100).toFixed(2)
      next();   
    });
    

    Change accuracy definition to:

    accuracy: {
         type: Number
    }