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

85
Vistas
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 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