【问题标题】:MongoDB Queries Async for loop results coming back emptyMongoDB查询异步循环结果返回空
【发布时间】:2021-10-16 03:11:58
【问题描述】:

我有一个 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);
    };
    }

rolesList 总是返回 [] 并且永远不会填充任何内容。

但是,如果我只是用相同的查询对单个 mongo 文档更新代码而不使用 for 循环,预期的响应就会返回,所以我知道与 MongoDB 的连接很好。

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

【问题讨论】:

  • 你能像这样包装 await 语句吗:response = (await db.collection("permissions").find({"_id": xxx})).toArray();
  • 是的,没有任何区别。
  • 请先将字符串id转换成ObjectId。
  • 您可以使用 var mongoose = require('mongoose'); 将字符串转换为对象 ID var id = mongoose.Types.ObjectId(string);

标签: javascript mongodb express npm


【解决方案1】:

你试过这种方法吗,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-22
    • 2014-07-20
    • 1970-01-01
    • 2018-01-17
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多