Pagination with Mongoose

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!


Show your support

Clapping shows how much you appreciated Mitch Masia’s story.