首页 > 解决方案 > 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 的连接性很好。

我究竟做错了什么?在这一点上拉我的头发!

标签: javascriptmongodbexpressnpm

解决方案


你试过这个方法吗,

  async function checkAuthorisation(list, groups) {
    const roleList = await Promise.all(
      list.map(async (item, index) => 
        await queryRoles(item._id)
      )
    );
    ...
  }

推荐阅读