How get document on mongoose findOneAndDelete middleware using Typescript?

Viewed 284

Can anyone help me with this problem?

I am using Typescript with mongoose v5.7.6 to create an API and this API manages users and vehicles so that the vehicle has the user ID and the user has a list of vehicle IDs (mongoose populate usage).

My problem is deleting a vehicle because I need to delete it in the user's vehicle list (cascade effect). I am using the findByIdAndDelete method of the vehicle model and have created pre-middleware for findOneAndDelete as the documentation (https://mongoosejs.com/docs/api/model.html#model_Model.findByIdAndDelete).

This findByIdAndDelete method triggers findOneAndDelete middleware successfully, but how can I get the document that is being deleted to get its attributes as the user ID?

If I use remove middleware, I can access the this element, but using findOneAndDelete middleware this does not match the document on Typescript.

How can I solve this problem?

1 Answers

According to mongoose documentation findOneAndDelete is a query middleware and this keyword in query middleware refers to the query, not the document.

If all you need is just the id of the document in question, then you can get it using this.getQuery()._id.

However, if you need more information than the once available in query then you have to query the database for the full document using the current query like so const document = await Model.find(this.getQuery()).

document variable will now contain the full document in question.

Related