Skip to content
Advertisement

countDocuments() is not working in api call

I am trying to get a count of products using api calls but in postman its keep loading

router.get(`/get/count`,  async (req, res) => {
  const productCount = await Product.countDocuments((count)=>count)
  if (!productCount) {
    res.status(500).json({ success: false });
  }
  res.send({
    productCount: productCount
  });
});

(node:28030) UnhandledPromiseRejectionWarning: MongooseError: Query was already executed: Product.countDocuments({})

without async and await also its not working

I try to catch the error and i got this error in postman

{
   "success": false,
   "error": "Query was already executed: Product.countDocuments({})"
}

code to catch error:

router.get(`/get/count`,   (req, res) => {
   Product.countDocuments((count)=>count).then((pcount)=>{
   if(pcount){
     return res.status(200).json({success:true})
   }else{
      return res.status(404).json({success:false})
   }
   }).catch((err)=>{
     return res.status(400).json({success:false, error:err.message})
   })

});

Advertisement

Answer

I think in Mongoose operations you want to either await or provide a callback, but not both. Attempting to do both causes it to internally execute the query twice.

Try just:

const productCount = await Product.countDocuments();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement