'MongoServerError: Limit value must be non-negative

I'm stuck when I get an error like this, I've been looking everywhere for a solution but haven't gotten any results. Please help me. thank you

Product.js "Routes"

router.get("/products/total/", productsCount)

Product.js "Controller"

exports.productsCount = async (req, res) => {
  let total = await Product.find({}).limit(0).estimatedDocumentCount().exec();
  res.json(total);
}

My error:

enter image description here



Solution 1:[1]

A better solution is to use "countDocuments" to get the count,

You can use this:

const count = await Product.countDocuments(query);

Examples:

const count = await Product.countDocuments({ categoryId : 'TEST' });

Or

Product.countDocuments({ categoryId : 'TEST' }, function (err, count) {
  console.log('Products count = ', count);
});

You can use below aggregation in mongodb 3.6

const result = await Product.aggregate([
  { "$facet": {
    "totalData": [
      { "$match": { categoryId : 'TEST' }}
    ],
    "totalCount": [
      { "$count": "count" }
    ]
  }}
])

with skip and limit

const result = await Product.aggregate([
  { "$facet": {
    "totalData": [
      { "$match": { categoryId : 'TEST' }},
      { "$skip": 10 },
      { "$limit": 10 }
    ],
    "totalCount": [
      { "$count": "count" }
    ]
  }}
])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1