使用异步等待执行多个数据库查询

时间:2019-02-06 07:00:48

标签: node.js asynchronous async-await

作为HTTP请求的一部分,我试图从几个mongodb集合中获取许多记录的计数。我有以下代码来处理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})
  });
});

在返回响应之前,如何使用async / await获取每个计数?

2 个答案:

答案 0 :(得分: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)
   }

  });
});

希望这个线索可以为您提供帮助。谢谢

答案 1 :(得分:0)

我建议使用Promise.all()。

方法如下:

app.get('/shopdetails/:id', function(req, res) {
   const getData = Shop.findOne({_id: req.params.id});
   const getDataEmployee = Employee.countDocuments({_shop: id});
   const getDataProduct = Product.countDocuments({_shop: id});
   Promise.all([getData, getDataEmployee, getDataProduct])
    .then((values) => { console.log(values) })
})