Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js MongoDB driver cursor does not count correctly

I'm having issues using MongoDB Node.js native driver version 2.2.29.

This is the code I'm running:

let cursor = db.collection( 'log' )
               .find({timestamp: { '$lte': 1498556839 }})
               .sort( { create_date_ttl: -1 } )
               .limit( 3 );

If I now run cursor.count() and handle the Promise I see the count is giving me 56 records instead of 3 (the limit specified).

cursor.count().then( (count) => {
   // count here is 56
});

However if I run cursor.count( function (err, count) {}) using callbacks, the count is correct only 3 records.

cursor.count( function (err, count) {
  // count here is 3 according to the limit specified.
});

Does anybody having same issue or can someone explain me how is this possible? Maybe I'm missing something, but seems to be ok according with the official documentation.

Thanks in advance.

like image 769
Moisés Belchín Avatar asked Mar 08 '23 18:03

Moisés Belchín


1 Answers

Explicity set first argument ( applySkipLimit ) to true, and then skip and limit will be appilied.

cursor.count(true).then( (count) => {
   // count here will be 3
});

It seems documentation is unclarified, because there is written that true should be default value. As mentioned in comment it is behaviour of callback.

like image 65
Jakub Kutrzeba Avatar answered Mar 11 '23 06:03

Jakub Kutrzeba