Skip to content

Deleting both the original object and its reference in a pre-delete hook #12107

Answered by revosw
revosw asked this question in Q&A
Discussion options

You must be logged in to vote

An alternative method could be to pass in not just _id, but also houseId when calling deleteOne

Ventilator.deleteOne({ _id: ventilatorId, houseId: houseId })

Because houseId is now added to the _conditions object, only a single call is needed in the hook now

ventilatorSchema.pre('deleteOne', {document: true}, async function (next) {
  await House.updateOne({ _id: this._conditions.houseId }, { $pull: { ventilator: this._conditions._id } })
  next()
})

But the downside is that if you accidentally refactor Ventilator.deleteOne({ _id: ventilatorId, houseId: houseId }) into Ventilator.deleteOne({ _id: ventilatorId }), now you will have no idea that the reference is not being deleted, and it is…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@vkarpov15
Comment options

@revosw
Comment options

Answer selected by revosw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants