I am trying to get a count of products using api calls but in postman its keep loading
JavaScript
x
12
12
1
router.get(`/get/count`, async (req, res) => {
2
const productCount = await Product.countDocuments((count)=>count)
3
if (!productCount) {
4
res.status(500).json({ success: false });
5
}
6
res.send({
7
productCount: productCount
8
});
9
});
10
11
(node:28030) UnhandledPromiseRejectionWarning: MongooseError: Query was already executed: Product.countDocuments({})
12
without async and await also its not working
I try to catch the error and i got this error in postman
JavaScript
1
5
1
{
2
"success": false,
3
"error": "Query was already executed: Product.countDocuments({})"
4
}
5
code to catch error:
JavaScript
1
13
13
1
router.get(`/get/count`, (req, res) => {
2
Product.countDocuments((count)=>count).then((pcount)=>{
3
if(pcount){
4
return res.status(200).json({success:true})
5
}else{
6
return res.status(404).json({success:false})
7
}
8
}).catch((err)=>{
9
return res.status(400).json({success:false, error:err.message})
10
})
11
12
});
13
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:
JavaScript
1
2
1
const productCount = await Product.countDocuments();
2