Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.96k stars 3.84k forks source link

how to get _doc instance in the pre update hook #7388

Closed Mdhaker closed 5 years ago

Mdhaker commented 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 ?

vkarpov15 commented 5 years ago

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.