【问题标题】:MongoServerError: Limit value must be non-negativeMongoServerError:限制值必须为非负数
【发布时间】:2022-02-01 23:15:33
【问题描述】:

当我遇到这样的错误时,我被卡住了,我一直在到处寻找解决方案,但没有得到任何结果。请帮我。谢谢

Product.js“路线”

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

Product.js“控制器”

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

我的错误:

enter image description here

【问题讨论】:

  • 我认为你可以使用 db.collection.countDocuments(query, options)?在这里,您将限制设置为 0,我认为这是不正确的。链接:mongoosejs.com/docs/api.html#model_Model.countDocuments
  • 仍然报错并且错误信息总是出现在控制台“MongoServerError: Limit value must be non-negative, but received: -9223372036854775808”

标签: javascript node.js mongodb mongoose


【解决方案1】:

更好的解决方案是使用“countDocuments”来获取计数,

你可以用这个:

const count = await Product.countDocuments(query);

例子:

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

或者

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

您可以在 mongodb 3.6 中使用以下聚合

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

带有跳过和限制

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

【讨论】:

  • 仍然报错并且错误信息总是出现在控制台“MongoServerError: Limit value must be non-negative, but received: -9223372036854775808”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
  • 2019-11-20
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
相关资源
最近更新 更多