Reputation: 7162
I am using MongoDB 2.6.7 where I have created Categories collection following the MongoDB mode tree structure with array of ancestors yet this model is really over complicating coding for me so I was wondering if someone can please advice me by the best model / schema design to follow in order to best achieve my Categories collection needs which are as follows:
A. Build a tree with unlimited levels of categories and sub-categories
B. For any node in the tree I can easily know the list of this node ancestors
C. For any node in the tree I can easily know if it has any child nodes or not
D. I can only create sub-nodes (sub-categories) to those categories not referenced by any item in the inventory
E. I can move any sub-node in the tree along with its child-nodes to a different node, sod for example if i have:
- 1
--11
---111
---112
---113
-----1131
-----1132
-----1133
--12
---121
---122
---123
so I can move node 113 with its sub-children 1131, 1132, 1133 and place 113 under 123 so that it will look like this:
- 1
--11
---111
---112
--12
---121
---122
---123
-----113
--------1131
--------1132
--------1133
My current categories collection design is as follows:
{ _id: "",
ancestors: [ ],
parent: ""
}
Thanks for your help.
Upvotes: 0
Views: 317
Reputation: 11671
Add in a field either for the immediate children or just to indicate that there are children:
{
_id: "",
ancestors: [<_id's>],
"children" : [<_id's>]
}
I'm not sure what the purpose of parent
was. This looks like a good schema design for A-C. D is something the application will need to enforce. E is not so bad to do with your design either, it just involves updating ancestors for all child nodes of the root node that is being relocated. B and E are in contention with each other - if you know the ancestors quickly by storing them on a node, you need to update all children when you relocate a subtree. B is most likely much more common than E, so the tradeoff of fast B for cumbersome E is reasonable.
Upvotes: 1