【问题标题】:How can I count docs in find in Mongodb? [duplicate]如何在 Mongodb 的 find 中计算文档? [复制]
【发布时间】:2019-10-14 09:22:20
【问题描述】:

我正在尝试计算 mongodb 请求中的文档。

我可以在toArray()-s 回调中计算count = docs.length,但总是给10。 A 可以做 2 个相同的请求,只需将 find 替换为 count 但这似乎是错误的

let count;
  db.get().collection('images').find({
     $and: [
     {tags: { $in: tags }}, 
     {date: {$gte: date.toISOString()}}, 
     {title:{$regex: query, $options: "$i"}}, 
  ]},
  (err, docs)=>{docs.toArray((err, res)=>{
    count= res.length
  })}
)
  .skip(0).limit(10).toArray((err, docs)=>{    
    res = {data:docs, dataLength:count }
    cb(err, res);
// })   
});   

我遇到了这个错误:TypeError: Cannot read property 'skip' of undefined

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    您可能总是收到 10 回,因为您在执行 .limit(10) 时特别说“给我 10 回”。现在,您收到该错误的原因是因为必须将.skip 添加到.find() 的末尾。您的查询应该是这样的:

    db.collection('images').find({
      $and: [
        {tags: { $in: tags }}, 
        {date: {$gte: date.toISOString()}}, 
        {title:{$regex: query, $options: "$i"}},
      ]
    }).skip(0).limit(10).toArray((err, docs) => {
      if (err) { console.log(err) }
      else {
        let res = {data:docs, dataLength:docs.length}
        // do any other logic here
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多