【问题标题】:Nodejs Mongodb perform multiple queries in one http callNodejs Mongodb 在一次 http 调用中执行多个查询
【发布时间】:2020-07-26 16:34:24
【问题描述】:

我创建了一个循环来执行多个查询,如下代码所示:

router.get('/getAverageClicks', async (req, res) => {
if(req.headers.token == process.env.API_TOKEN){
    let clicks = [];
    database.collection('locations').countDocuments().then(loccount => {
        for (var i = 0; i <= 10; i++) {
            var past = new Date();
            past.setDate(past.getDate() - i);
            var tpast = new Date();
            tpast.setDate(tpast.getDate() -1 -i)

            console.log(tpast);
            var query = { $and : [ {date: {$lte: past}},{date: {$gte: tpast}}]};
            collection.countDocuments(query).then(count => {
                console.log(count)
                clicks.push(count/loccount);
                if (clicks.length == 10){
                res.end(JSON.stringify(clicks.reverse()));
                res.status(200);
                }
            }); 
        }
    })

}else{
    res.end("Unauthorized")
    res.status(401)
}

});

现在的问题是 mongodb 异步返回数据,这意味着我有时会在不同的行中获取数据。我的问题是如何在同一行中执行 10 个不同日期的查询,以便每次都获得相同的数组。或者我如何改进我的循环以等待每个操作完成

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    您可以使用支持 async/await 的 for of 循环在发送响应之前等待每个查询。它可能如下所示:

    router.get('/getAverageClicks', async (req, res) => {
      if (req.headers.token == process.env.API_TOKEN) {
        const loccount = await database.collection('locations').countDocuments();
        let clicks = [];
        for (const i of [...new Array(11)].keys()) {
          var past = new Date();
          past.setDate(past.getDate() - i);
          var tpast = new Date();
          tpast.setDate(tpast.getDate() - 1 - i)
    
          console.log(tpast);
          var query = { $and: [{ date: { $lte: past } }, { date: { $gte: tpast } }] };
          const count = await collection.countDocuments(query);
          console.log(count)
          clicks.push(count / loccount);
        }
        res.end(JSON.stringify(clicks.reverse()));
        res.status(200);
      } else {
        res.end("Unauthorized")
        res.status(401)
      }
    });
    

    【讨论】:

    • 不幸的是,该行有时仍然不同。
    • 抱歉,兄弟误解了您的解决方案。你修好了谢谢
    • @Silas 没问题,很高兴听到这个答案很有帮助
    猜你喜欢
    • 2019-03-25
    • 2018-05-04
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 2020-02-11
    • 2011-10-07
    相关资源
    最近更新 更多