Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

mongo-cursor-pagination

mixmaxhq77.2kMIT9.1.1TypeScript support: included

Make it easy to return cursor-paginated results from a Mongo collection

mongo, pagination, cursor, database, fulltext, search, find

readme

mongo-cursor-pagination

Build Status

This module aids in implementing "cursor-based" pagination using Mongo range queries or relevancy-based search results. This module is currently used in production for the Mixmax API to return millions of results a day.

New

Background

See this blog post for background on why this library was built.

API Pagination is typically implemented one of two different ways:

  1. Offset-based paging. This is traditional paging where skip and limit parameters are passed on the url (or some variation such as page_num and count). The API would return the results and some indication of whether there is a next page, such as has_more on the response. An issue with this approach is that it assumes a static data set; if collection changes while querying, then results in pages will shift and the response will be wrong.

  2. Cursor-based paging. An improved way of paging where an API passes back a "cursor" (an opaque string) to tell the caller where to query the next or previous pages. The cursor is usually passed using query parameters next and previous. It's implementation is typically more performant that skip/limit because it can jump to any page without traversing all the records. It also handles records being added or removed because it doesn't use fixed offsets.

This module helps in implementing #2 - cursor based paging - by providing a method that make it easy to query within a Mongo collection. It also helps by returning a url-safe string that you can return with your HTTP response (see example below).

Here are some examples of cursor-based APIs:

Install

npm install mongo-cursor-pagination --save

Project language

This project has been converted to TypeScript to enhance type safety and improve developer tooling. All source files are now .ts files.

Usage

find()

Find will return ordered and paged results based on a field (paginatedField) that you pass in.

Call find() with the following parameters:

   Performs a find() query on a passed-in Mongo collection, using criteria you specify. The results
   are ordered by the paginatedField.

   @param {MongoCollection} collection A collection object returned from the MongoDB library's
      or the mongoist package's `db.collection(<collectionName>)` method.
   @param {Object} params
      -query {Object} The find query.
      -limit {Number} The page size. Must be between 1 and `config.MAX_LIMIT`.
      -fields {Object} Fields to query in the Mongo object format, e.g. {_id: 1, timestamp :1}.
        The default is to query all fields.
      -paginatedField {String} The field name to query the range for. The field must be:
          1. Orderable. We must sort by this value. If duplicate values for paginatedField field
            exist, the results will be secondarily ordered by the _id.
          2. Indexed. For large collections, this should be indexed for query performance.
          3. Immutable. If the value changes between paged queries, it could appear twice.
          4. Consistent. All values (except undefined and null values) must be of the same type.
        The default is to use the Mongo built-in '_id' field, which satisfies the above criteria.
        The only reason to NOT use the Mongo _id field is if you chose to implement your own ids.
      -sortAscending {Boolean} True to sort using paginatedField ascending (default is false - descending).
      -sortCaseInsensitive {boolean} Whether to ignore case when sorting, in which case `paginatedField`
        must be a string property.
      -next {String} The value to start querying the page.
      -previous {String} The value to start querying previous page.
   @param {Function} done Node errback style function.

Example:

const mongoist = require('mongoist');
const MongoPaging = require('mongo-cursor-pagination');

const db = mongoist('mongodb://localhost:27017/mydb');

async function findExample() {
  await db.collection('myobjects').insertMany([
    {
      counter: 1,
    },
    {
      counter: 2,
    },
    {
      counter: 3,
    },
    {
      counter: 4,
    },
  ]);

  // Query the first page.
  let result = await MongoPaging.find(db.collection('myobjects'), {
    limit: 2,
  });
  console.log(result);

  // Query next page.
  result = await MongoPaging.find(db.collection('myobjects'), {
    limit: 2,
    next: result.next, // This queries the next page
  });
  console.log(result);
}

findExample().catch(console.log);

Output:

page 1 { results:
   [ { _id: 580fd16aca2a6b271562d8bb, counter: 4 },
     { _id: 580fd16aca2a6b271562d8ba, counter: 3 } ],
  next: 'eyIkb2lkIjoiNTgwZmQxNmFjYTJhNmIyNzE1NjJkOGJhIn0',
  hasNext: true }
page 2 { results:
   [ { _id: 580fd16aca2a6b271562d8b9, counter: 2 },
     { _id: 580fd16aca2a6b271562d8b8, counter: 1 } ],
  previous: 'eyIkb2lkIjoiNTgwZmQxNmFjYTJhNmIyNzE1NjJkOGI5In0',
  next: 'eyIkb2lkIjoiNTgwZmQxNmFjYTJhNmIyNzE1NjJkOGI4In0',
  hasNext: false }

With Mongoose

Initialize Your Schema

const MongoPaging = require('mongo-cursor-pagination');
const mongoose = require('mongoose');
const counterSchema = new mongoose.Schema({ counter: Number });

Plug the mongoosePlugin.

// this will add paginate function.
counterSchema.plugin(MongoPaging.mongoosePlugin);

const counter = mongoose.model('counter', counterSchema);

// default function is "paginate"
counter.paginate({ limit: 10 }).then((result) => {
  console.log(result);
});

for paginate params refer the find section

const MongoPaging = require('mongo-cursor-pagination');
const mongoose = require('mongoose');

const counterSchema = new mongoose.Schema({ counter: Number });

// give custom function name

counterSchema.plugin(MongoPaging.mongoosePlugin, { name: 'paginateFN' });

const counter = mongoose.model('counter',
counterSchema);

// now you can call the custom named function

counter.paginateFN(params)
.then(....)
.catch(....);

You can also use the search function (as described below) like so;

// this will add paginate function.
counterSchema.plugin(MongoPaging.mongoosePlugin);

// give custom function name
// counterSchema.plugin(MongoPaging.mongoosePlugin, { searchFnName: 'searchFN' });

const counter = mongoose.model('counter', counterSchema);

// default function is "paginate"
counter.search('dog', { limit: 10 }).then((result) => {
  console.log(result);
});

search()

Search uses Mongo's text search feature and will return paged results ordered by search relevancy. As such, and unlike find(), it does not take a paginatedField parameter.

   Performs a search query on a Mongo collection and pages the results. This is different from
   find() in that the results are ordered by their relevancy, and as such, it does not take
   a paginatedField parameter. Note that this is less performant than find() because it must
   perform the full search on each call to this function. Also note that results might change

    @param {MongoCollection} collection A collection object returned from the MongoDB library's
       or the mongoist package's `db.collection(<collectionName>)` method. This MUST have a Mongo
       $text index on it.
      See https://docs.mongodb.com/manual/core/index-text/.
   @param {String} searchString String to search on.
   @param {Object} params
      -query {Object} The find query.
      -limit {Number} The page size. Must be between 1 and `config.MAX_LIMIT`.
      -fields {Object} Fields to query in the Mongo object format, e.g. {title :1}.
        The default is to query ONLY _id (note this is a difference from `find()`).
      -next {String} The value to start querying the page. Defaults to start at the beginning of
        the results.

Example:

const mongoist = require('mongoist');
const MongoPaging = require('mongo-cursor-pagination');

const db = mongoist('mongodb://localhost:27017/mydb');

async function searchExample() {
  await db.collection('myobjects').ensureIndex({
    mytext: 'text',
  });

  await db.collection('myobjects').insertMany([
    {
      mytext: 'dogs',
    },
    {
      mytext: 'dogs cats',
    },
    {
      mytext: 'dogs cats pigs',
    },
  ]);

  // Query the first page.
  let result = await MongoPaging.search(db.collection('myobjects'), 'dogs', {
    fields: {
      mytext: 1,
    },
    limit: 2,
  });
  console.log(result);

  // Query next page.
  result = await MongoPaging.search(db.collection('myobjects'), 'dogs', {
    limit: 2,
    next: result.next, // This queries the next page
  });
  console.log(result);
}

searchExample().catch(console.log);

Output:

page 1  { results:
   [ { _id: 581668318c11596af22a62de, mytext: 'dogs', score: 1 },
     { _id: 581668318c11596af22a62df, mytext: 'dogs cats', score: 0.75 } ],
  next: 'WzAuNzUseyIkb2lkIjoiNTgxNjY4MzE4YzExNTk2YWYyMmE2MmRmIn1d' }
page 2 { results:
   [ { _id: 581668318c11596af22a62e0, score: 0.6666666666666666 } ] }

Use with ExpressJS

A popular use of this module is with Express to implement a basic API. As a convenience for this use-case, this library exposes a findWithReq function that takes the request object from your Express middleware and returns results:

So this code using find():

router.get('/myobjects', async (req, res, next) => {
  try {
    const result = await MongoPaging.find(db.collection('myobjects'), {
      query: {
        userId: req.user._id
      },
      paginatedField: 'created',
      fields: { // Also need to read req.query.fields to use to filter these fields
        _id: 1,
        created: 1
      },
      limit: req.query.limit, // Also need to cap this to 25
      next: req.query.next,
      previous: req.query.previous,
    }
    res.json(result);
  } catch (err) {
    next(err);
  }
});

Is more elegant with findWithReq():

router.get('/myobjects', async (req, res, next) => {
  try {
    const result = await MongoPaging.findWithReq(req, db.collection('myobjects'), {
      query: {
        userId: req.user._id
      },
      paginatedField: 'created',
      fields: {
        _id: 1,
        created: 1
      },
      limit: 25 // Upper limit
    }
    res.json(result);
  } catch (err) {
    next(err);
  }
});

findWithReq() also handles basic security such as making sure the limit and fields requested on the URL are within the allowed values you specify in params.

Number of results

If the limit parameter isn't passed, then this library will default to returning 50 results. This can be overridden by setting mongoPaging.config.DEFAULT_LIMIT = <new default limit>;. Regardless of the limit passed in, a maximum of 300 documents will be returned. This can be overridden by setting mongoPaging.config.MAX_LIMIT = <new max limit>;.

Alphabetical sorting

The collation to use for alphabetical sorting, both with find and aggregate, can be selected by setting mongoPaging.config.COLLATION. If this parameter is not set, no collation will be provided for the aggregation/cursor, which means that MongoDB will use whatever collation was set for the collection.

(!) Important note regarding collation (!)

If using a global collation setting, or a query with collation argument, ensure that your collections' indexes (that index upon string fields) have been created with the same collation option; if this isn't the case, your queries will be unable to take advantage of any indexes.

See mongo documentation: https://docs.mongodb.com/manual/reference/collation/#collation-and-index-use

For instance, given the following index:

db.people.createIndex({ city: 1, _id: 1 });

When executing the query:

MongoPaging.find(db.people, {
  limit: 25,
  paginatedField: 'city'
  collation: { locale: 'en' },
});

The index won't be used for the query because it doesn't include the collation used. The index should added as such:

db.people.createIndex({ city: 1, _id: 1 }, { collation: { locale: 'en' } });

Indexes for sorting

mongo-cursor-pagination uses _id as a secondary sorting field when providing a paginatedField property. It is recommended that you have an index for optimal performance. Example:

MongoPaging.find(db.people, {
  query: {
    name: 'John'
  },
  paginatedField: 'city'
  limit: 25,
}).then((results) => {
  // handle results.
});

For the above query to be optimal, you should have an index like:

db.people.createIndex({
  name: 1,
  city: 1,
  _id: 1,
});

Running tests

To run tests, you first must start a Mongo server on port 27017 and then run npm test.

Future ideas

  • Add support to search() to query previous pages.

Publishing a new version

GH_TOKEN=xxx npx semantic-release --no-ci

changelog

9.1.1 (2025-10-31)

Bug Fixes

  • pagination error when paginatedField is not _id (b9c6dca)

9.1.0 (2025-07-04)

Features

Bug Fixes

  • encodePaginationTokens to encode plain objects (b6005bb)

9.0.1 (2025-04-01)

Bug Fixes

9.0.0 (2025-04-01)

⚠ BREAKING CHANGES

  • Updated to MongoDB driver v6 which requires:
  • BSON types must be from version 6.x
  • Node.js version compatible with MongoDB 6.x
  • Updated connection patterns and BSON handling
  • Removed support for deprecated methods

Signed-off-by: Alejandro Dominguez adborroto90@gmail.com

  • support mongo v6 and update mongoist

Features

  • enhance documentation (e98640e)
  • migrate to ts (1f8f10f)
  • support mongo v6 and update mongoist (5017252)
  • typescript convertion (54a54b7)
  • update deps and support mongo v7 (42aa306)
  • deps: bump mongoist & mongo memory server to use version 5.0.18 (f2b2343)
  • mongodb: add support to native mongodb 3+ (9c64b88)

Bug Fixes

  • lint fixes (2110240)
  • restore express dependency and improve findWithPagination function (6e7401d)
  • update collation type and simplify utils function (4ae455b)
  • deps: update dependency node to v18 (94c87f9)

8.1.3 (2023-02-14)

Bug Fixes

  • bump mongodb-memory-server dependency (0bb0e3d)
  • regenerate package-lock.json (659ec34)

8.1.2 (2022-08-26)

Bug Fixes

  • use the transpiled version in node 12 (a705377)

8.1.1 (2022-08-26)

Bug Fixes

  • properly page through undefs and nulls (0eb28e7)

8.1.0 (2022-08-25)

Features

8.0.1 (2022-08-24)

Bug Fixes

  • remove uses of the spread operator (7e8a8c9)

8.0.0 (2022-08-24)

⚠ BREAKING CHANGES

  • functional fixes and possible performance changes in aggregate.

Features

7.8.0 (2022-08-23)

Features

  • add a sortCaseInsensitive option to find and aggregate (#323) (f4543f6)

Bug Fixes

  • improve documentation and skip commit (e33a493)

7.7.0 (2022-08-16)

Features

  • allow collation as arg on find and aggregate (cdfcfcb)
  • turn global collation off for single query (c2ff6da)

Bug Fixes

7.6.1 (2021-11-18)

Bug Fixes

  • return _id when paginatedField is not set (1a056d7), closes #309

7.6.0 (2021-08-26)

Features

  • add support for aggregation hints (b90acd4)

7.5.0 (2021-08-26)

Features

  • extract/expose a function to encode pagination tokens (04dc7fa)

Bug Fixes

  • only export the function we need (8f80382)

7.4.0 (2021-03-08)

Features

  • mongoose-plugin: add search function (0efd73c)

Bug Fixes

  • skip bad commit message (4c85357)

7.3.1 (2020-08-10)

Bug Fixes

  • bson: fixes regression where string _ids were no longer supported (1487195)

7.3.0 (2020-05-06)

Features

  • find: add optional hint parameter for the cursor (17616da)

7.2.1 (2020-05-06)

Bug Fixes

Changelog

  • 7.2.0 Add support for COLLATION configuration parameter.

  • 7.1.0 Add support for aggregate.

  • 7.0.1 Update base64-url to fix security issue (https://github.com/mixmaxhq/mongo-cursor-pagination/pull/41 - thanks @pwiebe).

  • 7.0.0 Add findWithReq overrideFields support. Breaking: now throws errors on unusable fields/overrideFields, so check your inputs. Also changes our intersection mechanism, so it could cause backwards-incompatible changes to fields resolution. If causes unexpected backwards-incompatible changes, please file an issue!

  • 6.3.0 Can be used as a Mongoose plugin

  • 6.2.0 Added support for 'after' and 'before' parameters - thanks @lirbank

  • 6.1.0 Added support for native mongodb driver (https://github.com/mixmaxhq/mongo-cursor-pagination/pull/24 - thanks @lirbank)

  • 6.0.1 Fix issue where calling find with a paginated field that has dot notation e.g. start.dateTime produces an invalid next token.

  • 6.0.0 Breaking API change: mongo-cursor-pagination requires a Promise enabled mongodb instance from mongoist and returns Promises from find, findWithReq, and search rather than handling callbacks. Note: Although the library now uses async/await, it is still useable in node >= 6.9.0.

  • 5.0.0 Now 50 results are returned by default, and up to 300 results can be returned if the limit parameter is used. These can be overridden by setting mongoPaging.config.DEFAULT_LIMIT and mongoPaging.config.MAX_LIMIT respectively.

  • 4.1.1 Fixed bug that would overwrite $or in queries passed in.

  • 4.1.0 Adds sortAscending option to sort by the paginatedField ascending. Defaults to false (existing behavior).

  • 4.0.0 Breaking API change: next and previous attributes are now always returned with every response (in case the client wants to poll for new changes). New attributes hasPrevious and hasNext should now be used know if there are more results in the previous or next page. Before the change, next and previously could not be replied upon to know if there were more pages.

  • 3.1.1 Don't use let for backwards compatibility.

  • 3.1.0 findInReq() now accepts dot notation for fields. So you can pass ?fields=users.userId to only turn the userId property for users in the response.

  • 3.0.1 Fixed bug where the _id field was always returned when a paginatedField was used.

  • 3.0.0 Breaking API change: find() no longer accepts a string for limit. Added findWithReq.

  • 2.0.0 Changed API to so you now set global config on the config object instead of the root export itself (e.g. require('mongo-cursor-pagination').config.MAX_LIMIT = 100). The default MAX_LIMIT is now a more reasonable 25 instead of 100. Added search(). Fixed edge case where pages will be incorrect if paginatedField has duplicate values.

  • 1.1.0 Add MAX_LIMIT global setting to clamp

  • 1.0.0 Initial release