0

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++;
}
ahalekelly
  • 101
  • 1
  • I just realized that I could make 3 separate arrays using Array.push and then transform them into one array after they're full. There's probably a better solution though. – ahalekelly Oct 06 '16 at 17:35
  • Thanks that question looks like the right track, I just didn't know the keywords to search for! – ahalekelly Oct 06 '16 at 17:47

0 Answers0