Hierarchy / Tree: removing a node with all descendants


my application uses hierarchical data - tree-like structure. I store it in the MongoDB with parent- and children-node references as described in the official documentation. Sadly, there is no mention about how to remove nodes. There are some other tutorials around. but they only consider removing of terminal nodes/leafes.

Consider nodes with following relations

A -> B
B -> C
B -> D

This will result in an structure like

A - B

Removing the the Node B, without reconnecting or removing the nodes C and D will result in orphaned nodes.

I would like to focus on deleting the whole subtree and being able to get reactive changes on the client. So far, I realized I can not use the aggregation framework, cause it is not reactive and does not run on the client. What will be the most efficient way to delete the whole subtree ? I tried to search for recusrsive mongodb query but this usually points to $graphLookup

I would add an after remove hook on your collection and find any children of that item and remove them here. If the children are storred in the same collection this will be recursive. If not, add an after remove hook on the child collections too

1 Like

Hi @znewsham This is actually pretty smart, thank you. All my nodes are actually in the same collection and I also use collection.observeChanges in the tracker. There is this matb33:collection-hooks meteor package, would you recommend using it for this purpose ?

I would - note that there may be interactions between it, kadira and aldeed:simple-schema if you dont get the load order right

I am looking the collection-hooks package right now, just wondering whether shall I call collection.remove directly or call a Meteor.method with the remove call instead.

It doesn’t matter. So long as you define permissions it behaves the same. I would ensure that the hook is only defined on the server though, so it doesn’t run twice.

Also, some advise not to use client side methods as it’s hard to define the correct rules, but if your rules are simple it’s ok.