0
0
MongodbHow-ToBeginner · 3 min read

How to Paginate in Mongoose: Simple Guide with Examples

To paginate in mongoose, use the skip() method to skip a number of documents and limit() to restrict how many documents to return. Combine these with find() to fetch a specific page of results.
📐

Syntax

Pagination in Mongoose uses find() to select documents, skip(n) to skip the first n documents, and limit(m) to limit the number of documents returned to m.

This lets you fetch a specific page of results by calculating how many documents to skip based on the page number and page size.

javascript
Model.find(query).skip((pageNumber - 1) * pageSize).limit(pageSize)
💻

Example

This example shows how to get page 2 of users with 5 users per page.

javascript
const mongoose = require('mongoose');

// Define a simple User schema
const userSchema = new mongoose.Schema({
  name: String
});

const User = mongoose.model('User', userSchema);

async function paginateUsers(pageNumber, pageSize) {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  const users = await User.find()
    .sort({_id: 1})
    .skip((pageNumber - 1) * pageSize)
    .limit(pageSize);

  console.log(users);
  await mongoose.disconnect();
}

paginateUsers(2, 5);
Output
[{ _id: ObjectId("..."), name: "User6" }, { _id: ObjectId("..."), name: "User7" }, { _id: ObjectId("..."), name: "User8" }, { _id: ObjectId("..."), name: "User9" }, { _id: ObjectId("..."), name: "User10" }]
⚠️

Common Pitfalls

  • Not calculating skip correctly causes wrong pages or empty results.
  • Using large skip values can slow queries on big collections.
  • Not sorting results before paginating can lead to inconsistent pages.

Always use sort() before skip() and limit() to keep results stable.

javascript
/* Wrong: No sort, skip calculation off by one */
Model.find().skip(pageNumber * pageSize).limit(pageSize);

/* Right: Sort by _id, correct skip calculation */
Model.find().sort({_id: 1}).skip((pageNumber - 1) * pageSize).limit(pageSize);
📊

Quick Reference

Use this quick guide to paginate in Mongoose:

MethodPurposeExample
find()Select documentsModel.find({})
skip(n)Skip first n documentsskip((page - 1) * size)
limit(m)Limit to m documentslimit(pageSize)
sort()Order documents for consistent paginationsort({_id: 1})

Key Takeaways

Use skip() and limit() with find() to paginate results in Mongoose.
Calculate skip as (pageNumber - 1) * pageSize to get correct pages.
Always apply sort() before skip() and limit() for stable results.
Large skip values can slow queries; consider other pagination methods for big data.
Test pagination queries to ensure they return expected results.