我试图在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});
});