Stop 04 · REST API Design with ExpressTopics · 7/9

Filtering, Sorting and Search

Part of the MERN Stack Roadmap

In short

Users never want "all products". They want phones under Rs 15,000, sorted by price, matching "redmi". Your list endpoint turns those wishes, sent as query strings, into one safe database query.

List endpoints usually accept query parameters to filter (?category=books), sort (?sort=-price) and search (?q=phone), which the server turns into a database query.

The jaadu, as a shopkeeper, pulls a few phones from a crowded shelf and lines them up on the counter from smallest to biggest.

Think of it like this

Shopping with a helpful shopkeeper

At an electronics shop in Nehru Place, you say: only phones (filter), cheapest first (sort), and anything with "Redmi" in the name (search). The shopkeeper ignores requests that make no sense and brings back exactly that shelf.

Watch it happen

From query string to database query

?category=phones&sort=-price&q=redmi
Allow-list filters
Build sort
Add search
Run query

1/5React builds the URL from the filters the user picked.

The big ideas

What you need to know

Allow-list fields

Never pass req.query straight into find(). Copy only the fields you support, so users can't inject operators like $where.

Sort with a minus

A common convention: sort=price ascending, sort=-price descending, sort=-createdAt newest first.

Search options

Escaped $regex is fine for small collections. Use a text index or Atlas Search when data grows.

Combine with pagination

Filter, then sort, then skip and limit. Count with the same filter for an accurate total.

See it in code

Walk through the code

js
1const SORTABLE = new Set(["price", "createdAt", "name"]);2const escapeRegex = (s) => s.replace(/[.*+?^$()|[\]{}\\]/g, "\\$&");3 4function buildProductQuery(query) {5  const filter = {};6  if (typeof query.category === "string") filter.category = query.category;7  if (query.minPrice || query.maxPrice) {8    filter.price = {};9    if (query.minPrice) filter.price.$gte = Number(query.minPrice);10    if (query.maxPrice) filter.price.$lte = Number(query.maxPrice);11  }12  if (typeof query.q === "string" && query.q.trim()) {13    filter.name = { $regex: escapeRegex(query.q.trim()), $options: "i" };14  }15 16  const field = String(query.sort || "-createdAt").replace(/^-/, "");17  const sort = SORTABLE.has(field)18    ? { [field]: String(query.sort).startsWith("-") ? -1 : 1 }19    : { createdAt: -1 };20 21  return { filter, sort };22}

1/5Only these fields may be sorted. The helper escapes regex special characters in user input.

GET /api/products?category=phones&maxPrice=15000&sort=price&q=redmi becomes a safe filter and sort.

Save yourself the pain

Common mistakes

Oops

Product.find(req.query)

Do this instead

Build the filter yourself from an allow-list. Raw query objects can carry MongoDB operators and expose data.

Oops

Putting the user's search text straight into a regex.

Do this instead

Escape special characters first, or a search like "(" can throw an error or run very slowly.

Your mission

Build a product finder endpoint

~35 min

Quick check

Why should you avoid passing req.query directly to Product.find()?

Go deeper

  1. 1Allow only a known list of sortable and filterable fields.
  2. 2Combine filters, sort and pagination in one products endpoint.
  3. 3Test edge cases like an empty search, an unknown field and a negative price.

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