0

I'm trying to make an API end point in node.js which return a json array (im using mongodb as database).

I'm able to get an individual json object with different endpoint, but with this one I'm not able to get a json object which contains array of json objects.

The factitems array is always empty.

Code is below, what am I doing wrong?

app.get('/facts', (req, res) => {

  var idArr = getRandomArray();
 //a string array of 10 elements ["1","2","33"..]

  var factitems= []; //empty array
  console.log(idArr);

  for (var i = 0; i < idArr.length; i++) {
    // value of _id in db is int converted to string
    var details = { '_id': idArr[i] };

    db.collection('factslist').findOne(details, (err, item) => {
      if (err) {
        res.send({'error':'An error has occurred while fetching data'});
      } else {
        factitems.push(item);
        //console log here shows all items that are pushed to array
      }
    });

  }
  //the factitems array which was populated above is empty here
  console.log(JSON.stringify(factitems));

  //response object to be returned
  res.send({factitems});

});
Flying
  • 4,422
  • 2
  • 17
  • 25
  • 2
    Your problem has to do with *timing* not scope. – Quentin Jan 03 '18 at 11:48
  • 1
    The array is empty because you fill the array asynchronously and you send it synchronously. That is, you fill the array in the callback, but it has already sent the response. Use Promise.all() and send the array in the then(). – Abhyudit Jain Jan 03 '18 at 11:50
  • how do i use promise.all() and then()?, im very new to nodejs, express – MostlyAff Jan 05 '18 at 12:29

0 Answers0