12

Is there a way in MongoDB to have a foreign key with a 'ON DELETE CASCADE' functionality?

I know you can use DBRef as a sort of foreign key but when the item in a collection where the reference points to is removed, the reference returns null. But i want that the item where the reference belongs to gets removed. How do i do this?

Or do i need every time i remove things check references to it?

VDVLeon
  • 1,393
  • 1
  • 15
  • 26

2 Answers2

9

This feature doesn't exist now. If you want it. Add it on MongoDB Bugtracker

http://jira.mongodb.org

shingara
  • 46,608
  • 11
  • 99
  • 105
0

There is no builtin DELETE CASCADE but you can write your own login. Here is mine

Category.post('findOneAndDelete', async document => {
  if (document) await Stock.findOneAndDelete({ categoryId: document._id });
});

Details: I have to remove stock item if category will delete. So I use post middleware on Category delete and in that middleware i find the Stock Item which have that category and remove that too.

Sultan Aslam
  • 5,600
  • 2
  • 38
  • 44