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

272
Visualizações
How to access updated document during mongoose post update middleware?

I'm wondering if there is any reliable/reusable way to access the updated document during a mongoose post update middleware hook. All I seem to have access to is:

schema.post('update', function (result) {
  console.log(this) // Mongoose Query, no relevant doc info
  console.log(result) // Mongoose CommandResult, no relevant doc info
})

Thank you very much!

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

In the Query object you receive in the post hook, you have access to the parameters sent to the query. You can get it like this

_conditions: { id: 'cjauvboxb0000xamdkuyb1fta' }

const id = this._conditions.id

over 4 years ago · Santiago Trujillo Relatório

0

this also works on update/updateOne/updateMany

schema.post('update', function (documents) {
  this.model.find(this._conditions).then(documents => {
    console.log(documents.length)
  }
})
over 4 years ago · Santiago Trujillo Relatório

0

Schema.post('update') is only used in error handling (custom error messages)

// The same E11000 error can occur when you call `update()`
// This function **must** take 3 parameters. If you use the
// `passRawResult` function, this function **must** take 4
// parameters
Schema.post('update', function(error, res, next) {
  if (error.name === 'MongoError' && error.code === 11000) {
    next(new Error('There was a duplicate key error'));
  } else {
    next(error);
  }
});

If you wanted to add an updatedAt timestamp to every update() call for example, you would use the following pre hook.

Schema.pre('update', function() {
  this.update({},{ $set: { updatedAt: new Date() } });
});

Read official docs

over 4 years ago · Santiago Trujillo 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