如何为nodejs中的范围外的变量赋值

时间:2018-01-03 11:46:36

标签: javascript arrays json node.js mongodb

我试图在node.js中创建一个返回json数组的API端点(我使用mongodb作为数据库)。

我能够获得具有不同端点的单个json对象,但是使用此端点我无法获得包含json对象数组的json对象。

factitems数组始终为空。

代码在下面,我做错了什么?

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});

});

0 个答案:

没有答案