简体   繁体   中英

Hook in Mongoose works in PRE but doesn't work in POST

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;
    }
  })

'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;
    }
  })

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 < 1) {
        this._update.status = false
    }
    next();
});

Many thanks to him for his help as @hoangdv guided me to find the solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM