Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

315
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda