我想从几个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})
});
});
如何使用异步/等待返回响应之前得到每个计数?
尝试这个
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)
}
});
});
希望这条线索可以帮助你。谢谢