Nested requests to mongodb with nodejs and promised-mongo
<p>I have two mongodb collections with data structures like
1. "Taskgroups" collection</p>

<pre><code>{
        "taskgroup" : "M&amp;MS&amp;C_nEmpty", 
        "arg" : "1", "res" : ["1", "0", "0.1"] 
}
</code></pre>

<p>and
2. "Results" collection</p>

<pre><code>{
        "taskgroup" : "M&amp;MS&amp;C_nEmpty",
        "annotation" : {
            "fullDesc" : "result contains M MS C",
            "shortDesc" : "veryAwesomeRes",
            "colCount" : 4,
            "argCol": "kT",
            "cols" : ["M", "MS", "C"]
        }
}
</code></pre>

<p>I need to make nodejs with express endpoint which will return</p>

<pre><code>{
    "taskgroupsResCount" : [
        {
            "taskgroup": "DEADBEEF",
            "resultCount" : 1337
        },
        {
            "taskgroup": "1CED7EA",
            "resultCount" : 7331
        }
    ]
}
</code></pre>

<p>i.e. it shoul get list of "taskgroups" from one collection and count number of entries for each of them in other collection.
I wrote code with 'promised-mongo' like this:</p>

<pre><code>var db = pmongo(dbName);
var tgCollection = db.collection(tgCollectionName);
var resCollection = db.collection(resCollectionName);
var resultArray = [];
tgCollection
.find()
.forEach(function(tg){
    var taskGname = tg.taskgroup;
    console.log(taskGname);
    resCollection
    .find({"taskgroup" : tg.taskgroup})
    .then(function(resArray){               //func1
        console.log(resArray.length);
        resultArray.push(resArray.length);
    });
})
.then(function(){                           //func2
    console.log(resultArray);
});
</code></pre>

<p>but "taskGname" variable is not reachable from "func1" and "func2" does not prints anything.
What's wrong with my code? How to rewrite it in better way? Is it possible to make it in one request to mongodb with aggregation or other stuff? 
Thank in advance.</p>