This is the first of two blog posts about my mongoose plugin category-tree. The plugin is designed to automate save a series of hierarchical catagories by passing the most specific category to the save callback when saving an item to the database. In order to accomplish this task, the app needs to have a taxonomic tree containing all the category names in the system, and a set of names for each of the categories. A code example will serve to illustrate what I mean:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Each property of the ‘productTree’ object is a potential label for one of the categories, and the categories correspond exactly to properties of a mongoose schema. To set the categories properly you need to be able to find a path through the productTree, and that problem will serve as the subject of this post. My algorithm for finding a path through a tree is described below. The following assumes we are keeping track of an array ‘path’, a boolean ‘done’ and a ‘result’ variable.
- Iterate over the child nodes of the current node.
- If done is false, check to see if the current child is our target node.
- If the current child is our target push it to the path array, set result to path and done to true.
- If the current child is not our target, examine the current child for children
- If the child has children, set the child to current node and start over at step one. Otherwise do nothing.
- If the iteration of the current level finished and done is still false, pop the last node out of the path aray.
The above algorithm tries every path through the tree, keeping a record of each path as it progresses. If a given path ends with a negative result, the path leading to that result will be popped off the record. Here is the code in JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
|
When a new item is saved to the database none of the categories need to be filled out, simply passing the most specific category as the first argument to the save function is sufficient. How this is accomplished is covered in the next blog post, which covers the integration of an app with the Node.js mongoose module.