Home > Enterprise >  How can I delete cascade documents in mongoose?
How can I delete cascade documents in mongoose?

Time:11-24

I have a collection called Category with data structure defined like that:

{
  _id: 1,
  parent: null // ref to Category model
},
{
  _id: 2,
  parent: 1
},
{
  _id: 3,
  parent: 2
}

Now, I want to delete the document at _id: 1 and want to make sure its children have also deleted, means the document with _id: 2 will be deleted because its parent is the document with _id = 1 and the _id: 3 with parent id is 2 will be also deleted. Keep going like this until we have no related documents.

Do you have any suggestions or documents that I can refer to? Many thanks!

I don't have much experience in mongoose, I tried with recursive solution but I don't think it's a good way.

CodePudding user response:

I think you should try 'pre' remove middleware

https://mongoosejs.com/docs/middleware.html#pre


And look to answer here Cascade style delete in Mongoose

  • Related