Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

});
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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();
about 4 years ago · Juan Pablo Isaza Report

0

If you want to count all the products in your product collection, try this

db.product.countDocuments({})
about 4 years ago · Juan Pablo Isaza Report

0

router.get(`/get/count`,  async(req, res) => {
  let productCount = await Product.countDocuments();

  if(!productCount){
    res.send(500).json({success:false})
  }

  res.send({productCount: productCount})
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!