Home > Software design >  Mongooes query inside foreach not working
Mongooes query inside foreach not working

Time:11-04

this code not working, date = 112022. i need count of multiple table data with corporateID matching key. and use some math to culculate some more data. problem in query inside foreach. please help in this or tel if there any better option.

router.post('/BWreport', async function(req, res, next){
const month = req.body.date.slice(0, 2);
const year = req.body.date.slice(2, 6);
const nextmonth = parseInt(month)   1;
try{
var cname = await corporate.find().select('corporateID username').lean();
        cname.forEach(function(c, await){
         c["totalcases"] = verification_req.find({ createdAt: { $gt: year '-' month, $lt: year '-' nextmonth} }).where({'user_id':c.corporateID}).count();
        });
        return res.json({ response:true, data:cname });
        }catch(err){
        return res.json({ response:false, data:err  });
      }
});
{
"response": false,
"data": {}
}

desired output

data: [
        {
            "_id": "61d3f90340b6cad5974ca50a",
            "username": "SB Demo",
            "corporateID": "SB00001",
            "totalcases": "0"
        },
        {
            "_id": "62266f20fa0eb7a8fbe7d82a",
            "corporateID": "SB00002",
            "username": "NeoGrowth",
            "totalcases": "1"
        }]

CodePudding user response:

Use : for-of Loop & countDocuments({})

router.post('/BWreport', async function(req, res, next){

    const monthno = req.body.date.slice(0, 2);
    const yearno = req.body.date.slice(2, 6);
    const nextmonth = parseInt(monthno)   1;
    try{
      var cname = await corporate.find().select('corporateID username').lean();
      for(let c of cname){
         c["totalcases"] = await verification_req.countDocuments({ 'user_id':c.corporateID, createdAt: { $gt: year '-' month, $lt: year '-' nextmonth}});
      }

      return res.json({ response:true, data:cname });
     }catch(err){
        return res.json({ response:false, data:err  });
     }
});
  • Related