我想在 api 中使用循环返回数据。 但你知道 foreach 循环是异步的,而我的 allData json 对象每次都是 null。 我希望 json 对象不为空。 这就是为什么......我想在下面进行同步循环
var allData = [];
router.get('/user', function (req, res, next) {
var cursor = mdb.collection('USERS').find();
cursor.forEach(function (doc) {
allData.push(doc);
console.log(doc);
})
console.log(allDaTa);
});
打印:
[ ] //<-- my json object is null (allData)
<br><br>
{
_id: 5830ce676b184b1210d66749,
USERNAME: 'burakgumus'
}
我再说一遍<br><br>
我希望 json 对象不为空,并且我不想 cursor.toArray().<br>
最佳答案
您需要将回调函数传递给您的查询。因为它是一个异步调用,稍后当您完成其余代码时将返回结果:
var allData = [];
router.get('/user', function (req, res, next) {
mdb.collection('USERS').find({}).toArray(function(err, cursor) {
cursor.forEach(function (doc) {
allData.push(doc);
console.log(doc);
});
console.log(allDaTa);
next();
});
});
关于node.js - 从集合中获取并迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41171991/