0

I am trying to count docs in mongodb request.

I can count count = docs.length in toArray()-s callback but allways gives 10. A can do 2 same requests just replace find to count but it seems wrong

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

I am getting this err: TypeError: Cannot read property 'skip' of undefined

1 Answers1

0

You're probably always receiving 10 back because you are specifically saying "give me 10 back" when you do .limit(10). Now, the reason you are getting that error is because .skip has to be added to the end of the .find(). This is what your query should look like:

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
  }
})
Isaac Vidrine
  • 1,568
  • 1
  • 8
  • 20