Chapter 74: Node.js MongoDB Limit

limit() in MongoDB queries with Node.js + Mongoose (2025–2026 style).

We will go through this slowly and carefully, as if I’m sitting next to you right now — typing code, running it, looking at results in the terminal and in MongoDB Compass, explaining every decision, every trap, and every production nuance.

1. Mental model — What does .limit() actually do?

JavaScript

→ Returns at most 10 documents that match the query.

JavaScript

→ Skips the first 20 matching documents, then returns the next 10 (rows 21–30).

Together, .skip() + .limit() = pagination.

But:

  • .limit() alone is very useful even without skip
  • .skip() becomes very slow when the number is large (tens of thousands+)
  • Most real applications use cursor-based pagination instead of skip for large datasets

2. Why we care so much about LIMIT

Real-world problems without proper limit:

  • API returns 10,000+ documents → frontend hangs, network timeout, memory crash
  • Attacker requests ?limit=1000000 → server dies or becomes very slow
  • No pagination metadata → frontend doesn’t know how many pages exist

Good LIMIT usage solves:

  • Performance
  • Security (rate limiting + max limit)
  • Good API UX (total count, hasNext, hasPrev)

3. Project setup (realistic & modern)

Bash

tsconfig.json

JSON

package.json scripts

JSON

.env.example

text

4. MongoDB connection

src/config/mongodb.ts

TypeScript

src/config/env.ts

TypeScript

5. Realistic model with many documents

src/models/task.model.ts

TypeScript

src/seed-many.ts — create 100 tasks

TypeScript

Run once:

Bash

Now we have 100 tasks — perfect for testing pagination.

6. Basic LIMIT usage

src/controllers/task.controller.ts

TypeScript

Note: Without .sort(), order is not guaranteed — usually insertion order, but you should never rely on it.

7. LIMIT + sort (most common real usage)

TypeScript

8. Full pagination — page + limit (classic style)

TypeScript

Test URLs

  • GET /api/tasks/paginated?page=1&limit=10
  • GET /api/tasks/paginated?page=3&limit=20

9. Dynamic LIMIT (user-controlled — safe way)

src/controllers/task.controller.ts

TypeScript

Security & UX rules

  • Never trust req.query.limit directly
  • Always clamp it: Math.min(100, Math.max(1, limit))
  • 100 is a reasonable max for most APIs (adjust per use-case)

Very common beginner mistake

TypeScript

Correct — always coerce & validate

TypeScript

10. Summary – MongoDB .limit() best practices in Node.js 2025–2026

Best Practice Why it matters Recommended pattern
Never trust client limit value Prevents DoS / memory explosion `Math.min(100, Math.max(1, Number(req.query.limit)
Always combine with .sort() Order is otherwise undefined .sort({ createdAt: -1 }).limit(10)
Use .lean() for read-only lists 2–5× faster – plain objects .find().lean().limit(20)
Use cursor-based pagination for large data .skip() becomes very slow on big offsets { _id: { $gt: lastId } }.limit(pageSize)
Use indexes on sorted fields 10×–1000× faster schema.index({ createdAt: -1 })
Return pagination metadata Great API UX { total, totalPages, hasNext, hasPrev }
Log query time in production Find slow endpoints Add timing middleware or use mongoose.set(‘debug’, true) temporarily

Which direction would you like to go much deeper into next?

  • Login + JWT authentication with MongoDB
  • Full task CRUD (create/read/update/delete + ownership check)
  • Advanced pagination (cursor-based, infinite scroll, keyset pagination)
  • Text search + relevance sorting
  • Aggregation pipeline examples (group, match, unwind, etc.)
  • Performance tuning (indexes, .explain(), profiling)

Just tell me what you want to build or understand next — I’ll continue with complete, secure, production-ready code and explanations. 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *