Closed Mdhaker closed 5 years ago
I'm trying to update a field from other existing field when they are update, this is my code
`schema.pre('findOneAndUpdate', function() { debugger let _this = this.model(); if(this.getUpdate()['$set']) { let targetStats = Object.keys(this.getUpdate()['$set'])[0].split(".")[0]; let dayIndex = Object.keys(this.getUpdate()['$set'])[0].split(".")[1]; switch(targetStats) { case "bills":{ console.log("calculating bills totals before updating");break; // create total object to be set with the update query let totalObject = {}; // spent budget totalObject[`${targetStats}.${dayIndex}.total.spentBudget`] = _this[`${targetStats}`][dayIndex][`count.training.sent.amout`] + _this[`${targetStats}`][dayIndex][`count.hosting.sent.amout`]; console.log("Total calculated ",totalObject); this.update(totalObject); } default:console.warn("unhandled update query"); } } });`
I tried to use this.model() to get _doc instance but it seems to be the model instance, do I need another query to have the doc ?
You would need to actually load the doc first, so this would have to be in a post('findOneAndUpdate'). Before you execute findOneAndUpdate(), Mongoose doesn't have access to the actual doc being updated.
post('findOneAndUpdate')
findOneAndUpdate()
I'm trying to update a field from other existing field when they are update, this is my code
I tried to use this.model() to get _doc instance but it seems to be the model instance, do I need another query to have the doc ?