I need to create a large 2 dimensional array of Mongodb count objects. Currently I have a for loop that makes all the queries and then I'm trying to insert into the array using the Promise.then function, but all of the values get inserted into the last row, because Promise.then uses the index state at the time that the Promise finishes, not when it was called. Because it's a 2D array, I can't just use Array.push. One way to fix this would be to pass a value into Promise.then at the time it's called, but I don't see a way of doing that.
Here's a code example of one of the things I tried:
for(var x = startVal; x < endVal; x += stepSize) {
array[i] = [x];
db.collection('collection').find({fieldA: {$gt: x}).count().then(function(val) {array[i][1] = val;});
db.collection('collection').find({fieldB: {$gt: x}).count().then(function(val) {array[i][2] = val;});
i++;
}