0

I have a collection where an Item can be anothers parent and at the same time be another's child(it has a ItemCode and a ParentCode which is ItemCode of its parent).it may have multiple childs. I want to find all childrens of firstItemCode.at first I find every Item with ParentCode equal to first ItemCode then I do it again for every child found.like so:

var totals = [];
collection.find({'parentCode': firstItemCode.toString()}).then(function(d) {
        // console.log(d);
        d.forEach(function(u){
            totals.push({'itemCode': u['itemCode'], 'name':u['name'], 'name': u['price']});
            collection.find({'parentCode': u['itemCode'].toString()}).then(function(d1){
                d1.forEach(function(u1){
                    totals.push({'itemCode': u1['itemCode'], 'name':u1['name'], 'name': u1['price']});
                    collection.find({'parentCode': u1['itemCode'].toString()}).then(function(d2){
                        d2.forEach(function(u2){
                            totals.push({'itemCode': u2['itemCode'], 'name':u2['name'], 'name': u2['price']});
                            collection.find({'parentCode': u2['itemCode'].toString()}).then(function(d3){
                                console.log(totals);
                            });
                        });
                    });
                });
            });
        });

});

I want to do this until there is no more items in collection with a parent code equal to last item's code

I tried this tutorial but I got confused... I dont know how to fit forEach in chaining. Can anyone help me do this in a loop so I dont have to copy this 100 times?

0 Answers0