2

I am trying to get the count of a number of records from a few mongodb collections as part of an http request. I have the following code to process the http request but have some confusion getting other information.

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})
  });
});

How do I use async/await to get each count before returning the response?

2 Answers 2

2

Try this

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)
   }

  });
});

Hope this clue can help you. Thank you

Sign up to request clarification or add additional context in comments.

1 Comment

I would suggest adding a try-catch block. Otherwise good answer.
0

I would recommend to use Promise.all().

Here's how:

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) })
})

2 Comments

Does this run calls async instead of waiting for previous promise to resolve in the await functions?
Promise.all has a purpose to solve. It waits for the previous promise to be completed first and then moves to another promise. Now if any process fails, then it rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message/error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.