Pagination with Mongoose

Mitch Masia
Jul 31, 2017 · 2 min read

If you’re working with lists of data, you’ve probably seen the need for pagination. If we have 500 items in a list, that’s a lot of data to query for and send to the client in one request. Let’s see how can split that up.

At Hexient Labs, we enjoy using MongoDB and Mongoose when we work with Node. When we need pagination, we turn to the awesome mongoose-paginate package by Edward Hotchkiss. This plugin makes it fairly trivial to add robust pagination to your models.

Install Dependencies

npm install --save mongoose-paginate

Then inside your schema file:

/**
* Post.js
* @desc Post is a blog post you might see on Medium
* @desc Paginate Posts so we don't retrieve them all at once
*/
const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate');
const PostSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
featured_image_url: {
type: String,
required: false,
},
{
timestamps: true,
},
});
PostSchema.plugin(mongoosePaginate);module.exports = mongoose.model('Post', PostSchema);

Note that we used the mongoosePaginate plugin here to tell the model itself that we should be able to request paginated lists from it.

We can use this pagination functionality in our index query to Post:

Post.paginate({}, { page: 2, limit: 10 })
.then(response => {
/**
* Response looks like:
* {
* docs: [...] // array of Posts
* total: 42 // the total number of Posts
* limit: 10 // the number of Posts returned per page
* page: 2 // the current page of Posts returned
* pages: 5 // the total number of pages
* }
*/ })
.catch(handleQueryError);

Happy coding!


hexient-labs

Tiny thoughts from the team at Hexient Labs

Mitch Masia

Written by

Mitch is a developer, teacher, and entrepreneur building cool things at Guaranteed Rate.

hexient-labs

Tiny thoughts from the team at Hexient Labs

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade