Cursor is fast (MongoDB uses the index, no scanning of skipped docs) and stable (new items inserted between requests do not cause duplicates or skips). Offset is slow for large pages and unstable when items are inserted.
How to Implement Infinite Scroll in Node.js
Why use cursor pagination instead of offset for infinite scroll?
The answer
More FAQs in How to Implement Infinite Scroll in Node.js
Use cursor pagination. Fetch limit + 1 items. If you get limit + 1, there is more; pop the extra. Return nextCursor and hasMore. The frontend keeps calling with the last cursor until hasMore is false. Index the cursor field.
To know if there is more without a separate count query. If you get limit + 1 items, there is more (pop the extra). If you get limit or fewer, there is no more. Avoids the countDocuments query.
An index on the cursor field. For a feed sorted by createdAt descending, use schema.index({ createdAt: -1 }). Without an index, the cursor query is not faster than offset.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.