I have a graph of tag names like coffee, shoes etc. Each tag can have any multiple parent or child. I am making a tree of out that. I picked those nodes which don't have parent and start traversing from that. My mongo id
Taxonomy.find($or: [{ 'parent': { $exists: false } }]}).then((resp) => {
Promise.all(resp.map(resp) => getChildCategories(resp.children)).then(function(results) {
resp.children = results
res.json({resp});
}).catch(err => {
console.log(err)
});
});
But I stuck when there is a circular condition like a tag has a child and that child has the same parent so it got into circular condition. I am using es5 so no async await.
var visited_nodes = {"5a8c1c966ac6cb3c078fe727" : true};
//this map keep track of visited nodes
function getChildCategories(parentCategory){
return parentCategory.map(child => {
return new Promise((resolve,reject) => {
if(!visited_nodes[child]){
Taxonomy.findOne({_id : child}).then((resp) => {
visited_nodes[child] = true;
console.log(resp.children);
if(resp.children && resp.children.length > 0){
getChildCategories(resp.children)
.map(x => x).then(childresp => {
resp.children = childresp;
resolve([resp]);
})
}else{
resp.children = null;
resolve(resp);
}
}).catch(err => {
reject(err);
});
}else{
console.log("already visited")
return resolve({});
}
});
});
};
Due to asynchronous DB call, it is difficult to make a tree because map function returns null in the async call. Anyone has a solution about how to perform this