postman countDocuments()在API调用中不起作用

qij5mzcb  于 2022-11-23  发布在  Postman
关注(0)|答案(5)|浏览(171)

我试图获得使用api调用的产品计数,但在postman中它保持加载

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({})

没有异步和等待也不工作
我试图捕捉错误,我得到了这个错误在postman

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

捕获错误代码:

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

});
yqlxgs2m

yqlxgs2m1#

我 * 认为 * 在Mongoose操作中,您希望或者await或者提供回调,而不是两者都提供。尝试两者都提供会导致在内部执行查询两次。
请尝试:

const productCount = await Product.countDocuments();
de90aj5v

de90aj5v2#

如果要计算产品集合中的所有产品,请尝试以下操作

db.product.countDocuments({})
xzlaal3s

xzlaal3s3#

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

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

  res.send({productCount: productCount})
});
v8wbuo2f

v8wbuo2f4#

"有两种方法"

试试看,你不需要使用回调(count)=〉count

const express = require('express')
const router = express.Router();
const {Product} = require('../models/products')
const {Category} = require('../models/category')
const catchAsyncErrors = require('../middleware/catchAsyncError')
const mongoose = require('mongoose');

// Get all product 
router.get(`/`, async (req, res) => {
    let productList = await Product.find().populate('category')

    if(!productList) {
        res.status(500).json({
            success: false
        })
    }
    res.status(200).json({
        success: true,
        count: productList.length,
        productList

    });
})

router.get(`/count`, catchAsyncErrors(async(req, res) => {
    const countProductList = await Product.countDocuments();

    if(!countProductList){

        res.status(500).json({
            success: false
        })
    }
    res.send({
        success: true,
        countProduct: countProductList
    })

}))
b5lpy0ml

b5lpy0ml5#

您不需要包含((count)=>count)
请改用Product.countDocuments()

相关问题