Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!