首页 > 解决方案 > 如何在 Mongodb 的 find 中计算文档?

问题描述

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

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

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

标签: javascriptnode.jsmongodb

解决方案


你可能总是收到 10 回,因为当你这样做时,你特别说“给我 10 回” .limit(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
  }
})

推荐阅读