artsy / positron

Positron is Artsy Writer or the editorial tool and API for Artsy.
MIT License
85 stars 42 forks source link

fix: use collection.countDocuments instead of cursor.count #3140

Closed mc-jones closed 5 months ago

mc-jones commented 5 months ago

This patches #3131 to use collection.countDocuments instead of cursor.count which has a different behavior in the native mongodb@4.10 driver than the previously used mongojs library. Additionally, support it is deprecated.

cursor.count() will return the count of the artworks returned from the find cursor. However, what our clients are expecting is the total number of documents that will be returned from a passed-in query. This currently breaks pagination, as flagged by the editorial team 🔒 here.

const cursor = db
    .collection("articles")
    .find(query)
    .skip(offset || 0)
    .sort(sort)
    .limit(limit)

    // Will return the # of documents returned from the above query, factoring in the `limit`.  
    // If the value of `limit` is `15`, it will return `15` (or less if there are not `15` documents matching the query). 
    return cursor.count(cb)

    // Will return the total # of documents matching the query in the whole collection 
    return db.collection("articles").countDocuments(query, cb)
codecov[bot] commented 5 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Comparison is base (d1223f7) 83.5% compared to head (14abd0a) 83.5%.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #3140 +/- ## ===================================== Coverage 83.5% 83.5% ===================================== Files 197 197 Lines 5388 5388 Branches 978 978 ===================================== Hits 4500 4500 Misses 635 635 Partials 253 253 ```
joeyAghion commented 5 months ago

Good catch!