javascript - MongoDB查询异步循环结果返回空
问题描述
我有一个 ID 列表来查询我在 for 循环中使用的 Mongo,它总是返回一个空的 []。最初它一直返回承诺,所以我从forEach
标准 for 循环移到你在这里看到的,toArray()
这两者都导致了一个空的 []。
async function queryRoles(id) {
const db = await connectToMongo()
let response;
try {
response = await db.collection("permissions").find({"_id": xxx}).toArray();
console.log(await response);
} catch (error) {
console.log(error);
}
return response;
}
async function checkAuthorisation(list, groups) {
for (const item of list) {
const index = list.indexOf(item);
const rolesList = await queryRoles(item._id);
console.log(rolesList);
};
}
角色列表总是返回 [] 并且永远不会填充任何内容。
但是,如果我只是在不使用 for 循环的情况下对单个 mongo 文档使用相同的查询更新代码,预期的响应就会返回,所以我知道与 MongoDB 的连接性很好。
我究竟做错了什么?在这一点上拉我的头发!
解决方案
你试过这个方法吗,
async function checkAuthorisation(list, groups) {
const roleList = await Promise.all(
list.map(async (item, index) =>
await queryRoles(item._id)
)
);
...
}
推荐阅读
- java - Wikipedia API 获取随机文章
- ruby - 函数参数中的 Ruby 解构
- node.js - 是否可以从 jasmine 测试中执行 newman 集合
- jquery - 带有 flexslider 和 elevatezoom 的动画错误
- android - 如何从firebase数据库中具有多个子节点的多个节点检索数据
- html - CSS - 如何使在我的输入中输入的文本开始显示在框的左上角?
- javascript - 如何使用javascript反转xml的顺序
- dropbox-api - 将 Dropbox 文件路径正确转换为小写
- xml - 使用 xpath 从 xml 中提取值
- c# - Html Agility Pack Xpath 不工作