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?