Stop 07 · Mongoose ODMTopics · 8/8

Pagination with Mongoose

Part of the MERN Stack Roadmap

In short

You already know the theory of pagination. With Mongoose, it becomes a reusable helper that every list endpoint in your API can share, returning data and page details in one consistent shape.

Mongoose queries chain .sort(), .skip() and .limit() for page-based results, and countDocuments() gives the total so the React app can show page numbers.

The jaadu sits cross-legged turning the pages of a big decorated wedding album, each page holding a neat grid of photos.

Think of it like this

A photo album with numbered pages

A wedding album has hundreds of photos, ten per page, in date order. You can flip to page 7 and the cover tells you how many pages exist. The order never changes, so photos don't jump between pages. That's sort, skip, limit and countDocuments working together.

Watch it happen

GET /api/posts?page=3&limit=10

React
Controller
MongoDB

page=3&limit=10

1/5The user clicks page 3.

The big ideas

What you need to know

One helper

Write paginate(Model, filter, options) once and reuse it for posts, products and users.

Run queries in parallel

Promise.all with find and countDocuments halves the waiting time.

Count with the same filter

The total must use the exact same filter as the page, or page numbers won't match.

Cursor paging for feeds

For infinite scroll, use createdAt or _id less than the last item instead of skip. It stays fast on deep pages.

See it in code

Walk through the code

js
1// src/utils/paginate.js2export async function paginate(Model, filter, { page = 1, limit = 10, sort = { createdAt: -1 }, populate } = {}) {3  const safePage = Math.max(1, Number(page) || 1);4  const safeLimit = Math.min(50, Math.max(1, Number(limit) || 10));5 6  let query = Model.find(filter)7    .sort({ ...sort, _id: -1 })8    .skip((safePage - 1) * safeLimit)9    .limit(safeLimit);10  if (populate) query = query.populate(populate);11 12  const [data, total] = await Promise.all([query.lean(), Model.countDocuments(filter)]);13  return { data, page: safePage, limit: safeLimit, total, totalPages: Math.ceil(total / safeLimit) };14}15 16// Controller17export async function listPosts(req, res) {18  const filter = req.query.tag ? { tags: String(req.query.tag) } : {};19  const { page, limit } = req.query;20  res.json(await paginate(Post, filter, { page, limit, populate: { path: "author", select: "name" } }));21}22 23// Infinite scroll: next batch older than the last post seen24// Post.find({ createdAt: { $lt: lastCreatedAt } }).sort({ createdAt: -1 }).limit(10)

1/6Clean and cap page and limit, whatever the client sends.

A reusable helper. Each list endpoint becomes a two-line controller.

Save yourself the pain

Common mistakes

Oops

Calling countDocuments() with no filter while the page uses a filter.

Do this instead

Pass the same filter to both, so total and totalPages describe the filtered list.

Oops

Using skip for infinite scroll over a huge, fast-changing feed.

Do this instead

New posts shift every page. Use a cursor such as createdAt less than the last item's value.

Your mission

Paginate every list

~30 min

Quick check

Why add _id to the sort when sorting by createdAt?

Go deeper

  1. 1Build a paginated products endpoint that returns items, total and totalPages.
  2. 2Run the find and the count in parallel with Promise.all.
  3. 3Use .lean() on read-only list queries for faster plain objects.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge