首页 > 解决方案 > 如果在循环 node.js mongodb 中找到,则没有得到响应

问题描述

find在循环内使用 mongodb 查询,因为我需要运行find查询 5 次。我为此使用了以下代码:

let result = {};
let miles = ['5','10','15','25'];

let i = 0;
while (i < miles.length) {
  Shops.find({ 'shopInfo.address':{ $geoWithin:{ $centerSphere: [ [ 75.83183541365247, 30.902146005639267 ], miles[i] / 3959 ] } } }).then(response=>{
      if(i==4){
        result[miles[i]] = response.length;            
        res.json(result);
      }else{
        result[miles[i]] = response.length;            
        i++;
      }
  })
  .catch(err=>{
    console.log(err)
  }); 
}

当我在浏览器上点击 api 时。它没有返回任何东西,并且在控制台中出现以下错误:

错误图像

请帮助我,我该如何解决这个问题?

标签: node.jsmongodb

解决方案


会发生以下情况:

您的while循环运行并启动异步操作。但是,由于该异步操作尚未完成i++,因此不会执行,因此循环将永远运行,创建越来越多的异步操作来填满您的内存,最后 NodeJS 因为内存不足而崩溃。为防止这种情况,您不应使用异步任务同步迭代。循环内的await异步任务或异步任务然后等待它们:.mapmiles

 const entries = Promise.all(miles.map(mile =>        
    Shops.find({ 'shopInfo.address':{ $geoWithin:{ $centerSphere: [ [ 75.83183541365247, 30.902146005639267 ], mile / 3959 ] } } })
      .then(entry => ([mile, entry.length]))
 ));

 entries.then(entries => {
   const result = Object.fromEntries(entries);
   //...
});

 // Polyfill: Object.fromEntries
 if(!Object.fromEntries)
  Object.defineProperty(Object, "fromEntries", {
    value(entries) {
      const result = {};
      for(const [k, v] of entries)
        result[k] = v;
       return result;
     }
  });

推荐阅读