I have an embedded (updatable) tree structure in an array – considering the upcoming $slice abilities to select only parts of an array, I’m thinking of implementing a way to display only one (sub-)branch of the tree.
If I understand correctly, to do this efficiently, I’d have to save the path (grandparent.parent.child) in each item in the tree.
However, I can’t see a nice way of managing these paths (when updating), looks like these are my options:
- trusting client-side parameters blindly and just inserting to the array without verification of the path.
- fetching the entire document, compute the path and only then store the new item
What do you think? Branches cannot move around in the tree, they are only inserted/updated.
I just didn’t think about deep enough. At the time of insertion I currently have only a parent-id, but when I start having paths – I can use them to find the parent, then I can verify that the parent exist exactly in the same way as I’m currently doing it with parent-id.
The only problem with this approach is that I’d need to save the path even for branches that don’t have a parent (children of root).
Then, I can just search for them in the array with the mongo query and if they don’t exist the path is bogus and I stop the update.