异步使用等待做多的数据库查询

问题描述 投票:1回答:1

我想从几个MongoDB的集合多项纪录的数量作为HTTP请求的一部分。我有以下的代码来处理HTTP请求,但有一些困惑得到其他信息。

app.get('/shopdetails/:id', function(req, res) {
  Shop.findOne({_id: req.params.id})
    .exec(function(err, data) {
     if (err) { return res.status(500).send() };

     const id = data._id;
     //1. Get number of employees count from Employee collection
     //2. Get number of product count from Product collection
     // Each collection has a field _shop as a ref field so I can
     // do 
     // Employee.countDocuments({_shop: id}) or
     // Product.countDocuments({_shop: id})
  });
});

如何使用异步/等待返回响应之前得到每个计数?

node.js asynchronous async-await
1个回答
2
投票

尝试这个

app.get('/shopdetails/:id', async function(req, res) {
  try{
   const getData = await Shop.findOne({_id: req.params.id});
   const getDataEmploye = await Employee.countDocuments({_shop: id});
   const getDataProduct = await Product.countDocuments({_shop: id});
   // after that, you will get respons from Shop and Employe collection. Check console.log(getData), console.log(getDataEmploye), console.log(getDataProduct)
   //you can doing anything after get that collection data
   } catch(err){
    console.log(err)
   }

  });
});

希望这条线索可以帮助你。谢谢

© www.soinside.com 2019 - 2024. All rights reserved.