Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

306
Views
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;
    }
  })
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

'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;
    }
  })
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!