Skip to content

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 });
    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) => {
     return res.status(200).json({success:true})
      return res.status(404).json({success:false})
     return res.status(400).json({success:false, error:err.message})



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