MyInternships.in

Databases & Data Access

Node.js Pagination

Pagination limits how much a list endpoint returns. Offset pagination with skip and limit is simple; cursor pagination is correct and fast for large or fast-changing datasets.


What is Pagination in Node.js?

Pagination limits how much a list endpoint returns. Offset pagination with skip and limit is simple; cursor pagination is correct and fast for large or fast-changing datasets.

Pagination example

Offset and cursor pagination
JavaScript
// offset — simple, but skip() gets slow on deep pages
const page = Number(req.query.page ?? 1);
const limit = Math.min(Number(req.query.limit ?? 20), 100);

const [data, total] = await Promise.all([
  Job.find(filter).sort({ createdAt: -1 }).skip((page - 1) * limit).limit(limit).lean(),
  Job.countDocuments(filter),
]);

// cursor — constant time at any depth
const cursorFilter = req.query.after
  ? { ...filter, _id: { $lt: req.query.after } }
  : filter;
const data = await Job.find(cursorFilter).sort({ _id: -1 }).limit(limit).lean();
const nextCursor = data.at(-1)?._id ?? null;

Key points to remember

  • Cap the limit server-side; never let a client request everything.
  • skip(100000) makes the database walk every skipped document — avoid deep offsets.
  • countDocuments on a huge collection is itself expensive; consider an estimate.
  • Cursor pagination cannot jump to page 50, which is usually an acceptable trade.

Common mistakes with Pagination

  • Unbounded list endpoints that work in development and fall over in production.
  • Offset pagination over a list that changes constantly, so items shift between pages.

Node.js Pagination— Interview Questions & FAQs

Should I use offset or cursor pagination?+

Offset when users need numbered pages and the dataset is modest. Cursor for infinite scroll, feeds, and any large or frequently changing collection — it stays fast at any depth and does not skip or duplicate items.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships