I am wondering what the best way to do deep nested parent child relationships is using Feathers's recommended Association Method?
If my entries were:
[
{"name": "Grandpa", "id": 1, "parent": null},
{"name": "Mom", "id":2, "parent": 1},
{"name": "Baby", "id": 3, "parent": 2}
]
Then if I wanted to find the top parent of the tree, I would do a recursive get until I reach the top of the tree:
const family = app.service('/family')
function get_ancestors(childId, parents){
const child = family.get(childId)
if(child.parent){
parents.push(child.parent)
return get_ancestors(child.parent, parents)
} else {
return parents
}
}
But this seems clunky to me and not very extendable. Is there a better way? This seems like something fastJoin would do, but it is not under the "Recommended" approach to doing associations. I also don't see any examples of more than 3 levels in the guide, except in maybe the batch-loaders, And that looks to be a little more complex than we need here. What is the "recommended" way of traversing an ancestor tree using Feathers? Conversely, If I had Grandpa, how would I find Baby? Should my entries contain a "children" array that populates when a child is added with them as a parent? Or is there a better way of going from the top to the bottom of a parent tree?
What it comes down to is that Feathers is not an ORM, so handling associations depends a lot on the database and ORM you chose much the same as it would with other frameworks like Express or KoaJS. It means more flexibility but also that there isn't really the one true way to do this and the FAQ entry linked tries to cover the different options as good as possible.
fastJoin
does support nested associations but may be slower if you are using an SQL database where the ORM could handle optimizing the queries (Sequelize also supports nested includes). But it can be faster than Mongoose $populate
. Run some experiments to see which one works best. With parent/child relationships one thing to look out for is circular dependencies so you want to use something that can handle that.