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

83
Visualizações
Mongoose Middleware Hooks

I have the following database setup:

Post model that has a commentCount field corresponding to the number of comments defined as an integer.

Comment model that has a postId field as an ObjectId.

In order to ensure I don't make excess database calls I store the commentCount on the post model.

Currently, I have everything working but for clarity and data consistency, I am trying to determine the best way of setting up the following interaction:

I delete a comment with the following code:

const comment = await Comment.findById(postId)
const deletedComment = await comment.deleteOne()

This correspondingly triggers a deleteOne middleware pre save hook as follows:

CommentSchema.pre('deleteOne', { document: true, query: false }, async function() {
  // Update related post information
  await Post.findByIdAndUpdate(
    this.postId,
    { $inc: { commentCount: -1 }},
    { new: true }
  )
})

which is meant to keep the commentCount field synchronized with the number of comments corresponding to the post.

However, I'm curious how errors work in Mongoose middleware hooks. For example, if the middleware update fails on the post and I throw an error, will that also cancel the original comment.deleteOne() operation. I could handle this operation in the API route leveraging transactions to ensure all succeed but that seems a bit overkill for this scenario. Leveraging middleware hook seems cleaner.

Suggestions?

about 4 years ago · Juan Pablo Isaza
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