Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

317
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda