【问题标题】:Fetching an list of items from Mongoose and returning the results从 Mongoose 获取项目列表并返回结果
【发布时间】:2021-11-14 12:07:02
【问题描述】:

正如您从下面的代码中看到的那样,我正在尝试创建一个具有以下格式的对象数组:

[{Region: Africa, Countries: X, X, X}, {Region: Asia, Countries X, X, X}]

X 代替国家名称。我能够成功创建这个对象数组。

创建完这个对象数组后,我想做一个res.send 200 来发送数据。问题是,在所有以前的配置中,我都会收到一个错误,因为 res.send 会尝试执行多次。现在我正在尝试通过承诺来做到这一点,并使用Promise.all。我很确定我没有正确实现它,因为现在这段代码没有产生任何东西,而是没有产生任何输出。

这段代码非常接近它需要的位置......如果有人可以告诉我我在这里缺少什么,那就太好了。它必须与承诺有关。

router.get("/FRPListing", async (req, res) => {
  //Array of all regions
  //Have a country list

  //Holder Array
  let regCountryList = new Array()

  //New Array
  let countryList = new Array()
  countryList.push("Europe and UK", "Africa", "Middle East and Gulf", "Eurasia", "Asia", "Australasia", "North America", "Central America Caribbean", "South America", "Global")

  countryList.forEach(async function (value) {
    let EuropeUK = await FRPObj.find({Region: value}, 'Region Country').sort({Country: 1}).distinct('Country').exec()
    let EuropeUKRegCountryList = new Object()
    EuropeUKRegCountryList.Region = value
    EuropeUKRegCountryList.Countries = EuropeUK
    regCountryList.push(EuropeUKRegCountryList)
  })

  Promise.all(regCountryList).then(values => {
    res.send({status: 200, results: regCountryList})
  });
});

【问题讨论】:

    标签: javascript mongodb mongoose promise


    【解决方案1】:

    您的问题中似乎缺少信息。如果能发minimal reproducible example就更好了。

    我认为您不太了解 Promise.all 的用途,并且您正在使用它来包装数据数组,而这并没有做任何事情。

    相反,您应该构造一个 promise 数组(对数据服务的调用)并将 that 传递给 Promise.allPromise.all 将调用传递给它的所有承诺,并等待它们全部解决。

    在编写代码时,最好重命名一些变量以更清楚地了解意图。

    这样的事情应该很接近。例如,某些细节可能不正确,具体取决于您的服务调用实际返回的内容。此外,您可能需要处理错误情况!

    // You shouldn't need the `async` keyword decorating this function 
    // if you're handling the callback using promises.  If you were using 
    // "await" within the callback, for example, you would need it.
    router.get("/FRPListing", (req, res) => {
      const regions = ["Europe and UK", "Africa", "Middle East and Gulf", "Eurasia", "Asia", "Australasia", "North America", "Central America Caribbean", "South America", "Global"];
    
      const fetchCountries = [];
    
      // First, build an array of promises (your async calls to your data source)
      for (const region of regions) {
        fetchCountries.push(
          FRPObj.find({
            Region: region
          }, 'Region Country').sort({
            Country: 1
          }).distinct('Country').exec();
        );
      }
    
      // Promise.all will return a results array with one entry per 
      // promise, and they will be in the order in which the original 
      // promises were pushed into the array.  Because the order is 
      // preserved, you can look up the region from the regions.
      Promise.all(fetchCountries).then(results => {
        const aggregatedResults = [];
        for (let i = 0; i < regions.length; i++) {
          const region = regions[i];
          const countries = results[i];
          aggregatedResults.push({
            Region: region,
            Countries: countries
          });
        }
        res.send({
          status: 200,
          results: aggregatedResults
        });
      });
    });

    【讨论】:

    • 感谢您如此友善并花时间给我写这样一个深入而彻底的答案。我编写了代码(而不是复制粘贴),因此我可以欣赏它并了解它是如何工作的。 Promise 和 Mongoose 对我来说是一场斗争......直到今天。谢谢你说得这么清楚。我真的很感谢你的时间。
    • 太棒了!很高兴它有帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 2020-01-29
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多