【问题标题】:push is not working in map function in Node js推送在 Node js 中的地图功能中不起作用
【发布时间】:2020-07-21 11:23:27
【问题描述】:

我正在使用 Mongo DB,在从聚合查询中获取结果后,映射该查询的结果并尝试将结果推送到数组。在安慰该数组时,它返回一个空数组,但如果我们在地图内部进行控制台,则有 data 。下面是我的代码sn-p

let house = await House.aggregate([
    { $group: { _id: "$houseNumber", count: { $sum: 1 } } },
    { $match: { _id: { $ne: null }, count: { $gt: 1 } } },
    { $project: { houseNumber: "$_id", _id: 0 } },
  ]);

  var arr = [];
  house.map(async (hNo) => {
    var house2 = await House.find(
      { houseNumber: hNo.houseNumber },
      "houseNumber"
    );
    arr.push(house2);
  });
  
  console.log(arr);

我在想异步等待在这里制造问题。请帮我。非常感谢。

【问题讨论】:

  • 您不需要在house.map 循环中运行多个查询。您可以通过House.find( { houseNumber: { $in: house.map(h => h.houseNumber)}}, "houseNumber" ); 在单个查询中获取所有文档。但是您的代码甚至没有意义。您已经拥有来自聚合函数的 houseNumbers。你为什么要进行另一个多次查询,只通过你已经拥有的 houseNumber 获得一个 houseNumber?您想通过 House.find 实现什么目标??

标签: javascript node.js arrays mongodb


【解决方案1】:

.map 不支持异步功能

您可以使用Promise.all 等待每个异步函数结果。

let house = await House.aggregate([
    { $group: { _id: "$houseNumber", count: { $sum: 1 } } },
    { $match: { _id: { $ne: null }, count: { $gt: 1 } } },
    { $project: { houseNumber: "$_id", _id: 0 } },
]);

// Array of Promises
const promises = house.map(hNo =>
    House.find(
        { houseNumber: hNo.houseNumber },
        "houseNumber"
    );
)

// Array with each promise result
const arr = await Promise.all(promises);
  
// Now you able to log it
console.log(arr);

在安慰该数组时,它返回一个空数组 map 不等待异步函数结果,因此在记录 arr 时,您有一个空数组和 arr.length 待处理的 Promises。

【讨论】:

  • 谢谢@a-kon。它现在真的很好用,但我不知道 'Async function are not supported in .map' 。我在路由的多个异步函数中使用地图。这是正确的方式吗?还是以后会给我带来麻烦?
  • 你可以在异步函数中使用 map,反之亦然。支持异步函数作为 map 的回调,但结果不是函数结果的数组,而是 promise 的数组。
猜你喜欢
  • 1970-01-01
  • 2021-07-15
  • 2021-02-14
  • 2021-08-01
  • 2017-02-21
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
相关资源
最近更新 更多