【问题标题】:store multipule mongoose queries result in one array将多个猫鼬查询结果存储在一个数组中
【发布时间】:2021-05-12 05:23:21
【问题描述】:

我想请你帮忙,我正在尝试通过 axios 请求使用许多 id 搜索我的 mongoldb 数据,

我向节点发起一个包含所有 id 的请求,如下所示

 var data=new FormData()
   data.append("offered",offered)
  axios ({
    url:`http://localhost:5000/items/itemsDetail`,
    method:"POST",
    data:{offered:offered},

   })  

然后在后端节点模型中,我发起如下查询

 var offered=req.body.offered

  var responsed=[]

  offered.forEach(offer=>{
     item.findById([offer])
      .then(result=>{
       console.log(result)
      responsed.push(result)
     })

     res.json({result:response})

它单独工作并记录单个结果(“console.log(result)”),但是当我尝试收集它们并将[“responsed”变量数组]作为一次性响应发送回来时,我得到了一个axios 中的空对象响应?!

希望你明白我的意思!

我想发送多个查询并获得一次。

【问题讨论】:

    标签: node.js reactjs mongodb mongoose axios


    【解决方案1】:

    问题是item.findById是一个异步函数。

    为了返回所有数据,您需要等待每个item.findById完成。

    看下面的例子:

    // Used for the snippet to run without error
    const req = {
      body: {
        offered: [
          'foo',
          'bar',
        ],
      },
    };
    
    // Used to simulate the async function
    const item = {
      findById: ([d]) => new Promise((r) => setTimeout(() => r(`Response :: ${d}`), 100)),
    };
    
    // Used for the snippet to run without error
    const offered = req.body.offered;
    
    // Syntax used to be able to use async/await syntax
    (async() =>  {
    
      // Call every findById and wait for them to finish
      const response = await Promise.all(offered.map(offer => item.findById([offer])));
    
      console.log({
        result: response,
      });
    
    })();

    【讨论】:

      猜你喜欢
      • 2017-05-08
      • 1970-01-01
      • 2019-01-26
      • 2020-03-09
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 2020-02-03
      • 2011-07-02
      相关资源
      最近更新 更多