Offset pagination (skip(page * size)) is the first thing every MEAN tutorial teaches and the first thing that breaks in production. On a large collection skip makes MongoDB walk and discard every skipped document, so page 5,000 is far slower than page 1. Rows inserted while a user scrolls also cause duplicates or gaps. This tutorial replaces it with cursor (keyset) pagination across the whole stack: a MongoDB 8 compound index, an Express 5 endpoint with Zod validation, and an Angular 22 signals-based list.
Prerequisites
- Node.js 24 LTS, Express 5, Mongoose 8, MongoDB 8.0.
- Angular 22 with a standalone, zoneless app (see our modern MEAN app tutorial for the base setup).
Why skip/limit fails
// Slow at depth, unstable under writes
Post.find().sort({ createdAt: -1 }).skip(50000).limit(20);
Keyset pagination instead says "give me the 20 documents after the last one I saw". With a matching index MongoDB seeks straight to that position, so every page costs about the same.
Step 1: a sort key that is unique
createdAt alone is not unique, so two documents created in the same millisecond can be skipped or repeated. Add _id as a tiebreaker and index both:
import { Schema, model } from 'mongoose';
const articleSchema = new Schema({
title: { type: String, required: true },
tenant: { type: Schema.Types.ObjectId, required: true },
}, { timestamps: true });
// Equality field first, then the sort fields in the same direction as the query
articleSchema.index({ tenant: 1, createdAt: -1, _id: -1 });
export const Article = model('Article', articleSchema);
Step 2: encode the cursor
The cursor is opaque to clients. Encode the last document's sort values as base64url, so you can change internals later without breaking the API:
export const encodeCursor = (doc) =>
Buffer.from(JSON.stringify([doc.createdAt.toISOString(), String(doc._id)])).toString('base64url');
export function decodeCursor(cursor) {
const [createdAt, id] = JSON.parse(Buffer.from(cursor, 'base64url').toString());
return { createdAt: new Date(createdAt), id };
}
Because clients can send anything, decode inside a Zod refinement (next step) and treat failures as a 400. Never put the cursor into a query unvalidated; this is the same discipline that prevents NoSQL injection.
Step 3: the Express 5 endpoint
import express from 'express';
import { z } from 'zod';
import { Types } from 'mongoose';
import { Article } from './article.js';
import { encodeCursor, decodeCursor } from './cursor.js';
export const router = express.Router();
const Query = z.object({
limit: z.coerce.number().int().min(1).max(100).default(20),
cursor: z.string().max(200).optional().transform((value, ctx) => {
if (!value) return undefined;
try {
const c = decodeCursor(value);
if (Number.isNaN(c.createdAt.getTime()) || !Types.ObjectId.isValid(c.id)) throw new Error();
return c;
} catch {
ctx.addIssue({ code: 'custom', message: 'invalid cursor' });
return z.NEVER;
}
}),
});
router.get('/api/articles', async (req, res) => {
const { limit, cursor } = Query.parse(req.query);
const filter = { tenant: req.user.tenantId };
if (cursor) {
// Strictly "after" in (createdAt desc, _id desc) order
filter.$or = [
{ createdAt: { $lt: cursor.createdAt } },
{ createdAt: cursor.createdAt, _id: { $lt: new Types.ObjectId(cursor.id) } },
];
}
// Fetch one extra row to know whether another page exists
const rows = await Article.find(filter)
.sort({ createdAt: -1, _id: -1 })
.limit(limit + 1)
.lean();
const hasMore = rows.length > limit;
const items = hasMore ? rows.slice(0, limit) : rows;
res.json({
items,
nextCursor: hasMore ? encodeCursor(items.at(-1)) : null,
});
});
Notes: the limit + 1 trick avoids a separate countDocuments, which is itself expensive on large collections. A Zod failure is thrown from an async handler and Express 5 forwards it to your error middleware automatically. Keep req.query access read-only: in Express 5 it is a getter, which is why we parse into a new object.
Step 4: verify the index is used
const plan = await Article.find({ tenant }).sort({ createdAt: -1, _id: -1 }).limit(21).explain('executionStats');
console.log(plan.executionStats.totalDocsExamined); // should be ~21, not thousands
The winning plan should show an IXSCAN on tenant_1_createdAt_-1__id_-1 with no SORT stage. If you see a SORT stage, the index direction does not match the query. See our guide to MongoDB 8 index tuning for reading explain output.
Step 5: an infinite scroll list in Angular 22
A small service holds the state in signals:
import { Injectable, inject, signal, computed } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
interface Article { _id: string; title: string; }
interface Page { items: Article[]; nextCursor: string | null; }
@Injectable({ providedIn: 'root' })
export class ArticleFeed {
private http = inject(HttpClient);
readonly items = signal<Article[]>([]);
readonly loading = signal(false);
readonly error = signal<string | null>(null);
private cursor = signal<string | null>(null);
private started = signal(false);
readonly done = computed(() => this.started() && this.cursor() === null);
async loadMore() {
if (this.loading() || this.done()) return;
this.loading.set(true);
this.error.set(null);
try {
const params: Record<string, string> = { limit: '20' };
if (this.cursor()) params['cursor'] = this.cursor()!;
const page = await firstValueFrom(this.http.get<Page>('/api/articles', { params }));
this.items.update(list => [...list, ...page.items]);
this.cursor.set(page.nextCursor);
this.started.set(true);
} catch {
this.error.set('Could not load more articles.');
} finally {
this.loading.set(false);
}
}
}
The component renders the list and a "Load more" button, which is the most accessible and keyboard friendly option and a good first version:
import { Component, inject } from '@angular/core';
import { ArticleFeed } from './article-feed';
@Component({
selector: 'app-article-list',
template: `
<ul>
@for (a of feed.items(); track a._id) {
<li>{{ a.title }}</li>
}
</ul>
@if (feed.error()) {
<p role="alert">{{ feed.error() }}</p>
}
@if (!feed.done()) {
<button (click)="feed.loadMore()" [disabled]="feed.loading()">
{{ feed.loading() ? 'Loading...' : 'Load more' }}
</button>
} @else {
<p>You have reached the end.</p>
}
`,
})
export class ArticleList {
feed = inject(ArticleFeed);
constructor() { this.feed.loadMore(); }
}
To make it true infinite scroll, attach an IntersectionObserver to a sentinel element below the list (in a small directive) and call feed.loadMore() when it becomes visible. The service already guards against concurrent and finished loads, so repeated triggers are harmless. Keep track a._id so appended rows do not re-render existing ones.
Trade-offs to be honest about
- No random page jumps. Cursors support next/previous, not "go to page 40". For admin tables that need page numbers, keep offset pagination but cap the depth and require a filter.
- Changing sort order. Each sort option needs its own index, and the cursor must encode the matching fields. Whitelist sort fields instead of accepting arbitrary ones.
- Previous page. Reverse the comparison and sort, then reverse the result in memory.
- Total counts. If the UI needs one, use a cached or estimated count (
estimatedDocumentCountfor unfiltered collections) rather than counting on every request. - Sharded clusters. Include the shard key in the filter so queries can be targeted.
Checklist
- Compound index of equality fields, then sort fields, with
_idas tiebreaker. - Opaque, validated cursor;
limitcapped at a sane maximum. limit + 1instead of a count query.explain()confirmsIXSCANand noSORTstage.- Client state in signals, with error, retry and end-of-list states.
If your MEAN app slows down as data grows and you are not sure where the time goes, our performance tuning and MEAN stack consulting teams do this kind of work every week.