Using Mongoose hooks, I need that if the property called outstandingBalance has a value of zero, the status automatically changes to false.
Trying to do this using Mongoose's PRE hook works but only by re-invoking the request after outstandingBalance was already zero before. That is why I have decided to use the POST hook so that once the setting of outstandingBalance to zero is finished, it changes the property from statua to false.
This is the code that I use with PRE that works fine but is not really viable for what I need:
SaleSchema.pre('findOneAndUpdate', async function() {
const docToUpdate = await this.model.findOne(this.getQuery())
if (docToUpdate.outstandingBalance < 1) {
this._update.status = false;
}
})
So I decided to change PRE to POST but it never works:
SaleSchema.post('findOneAndUpdate', async function() {
const docToUpdate = await this.model.findOne(this.getQuery())
if (docToUpdate.outstandingBalance < 1) {
this._update.status = false;
}
})
CodePudding user response:
'POST' means all done, there is no action after that(the data is already updated), you have to save it again after setting the status to update the status.
PRE
hook is correct for your case, just change the condition: Checking on update data instead of current data
SaleSchema.pre('findOneAndUpdate', async function() {
const docToUpdate = await this.model.findOne(this.getQuery())
if (this._update.outstandingBalance < 1 || (!this._update.outstandingBalance && docToUpdate.outstandingBalance < 1)) {
this._update.status = false;
}
})
CodePudding user response:
This was the solution to be able to set the status to false depending on the outstandingBalance value using the Pre hook:
SaleSchema.pre('findOneAndUpdate', function (next) {
if(this._update.$set.outstandingBalance < 45 ) {
this._update.status = false
}
next();
});
Many thanks to him for his help as @hoangdv guided me to find the solution.