This module aids in implementing "cursor-based" pagination using Mongo range queries or relevancy-based search results. It is based on the mongo-cursor-pagination package but has a dedicated mongoose plugin (which keeps instance methods etc.) and support for Typegoose out of the box.
Demo project
A demo project can be found here: https://github.com/ExtraBB/typegoose-cursor-pagination-demo
Background
See this blog post for background on why this library was built.
API Pagination is typically implemented one of two different ways:
-
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.
-
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 typegoose-cursor-pagination --save
Usage
Plugin options
The plugin accepts the following options:
export interface IPluginOptions {
dontReturnTotalDocs?: boolean;
dontAllowUnlimitedResults?: boolean;
defaultLimit?: number;
}
findPaged()
findPaged()
will return ordered and paged results based on a field (sortField
) that you pass in.
Parameters
Call findPaged()
with the following parameters:
- params {IPaginateOptions} (The paginate options)
- _query {Object} (A mongo query)
- _projection {Object} (A mongo projection)
- _populate {string | PopulateOptions | (string | PopulateOptions)[]} (A mongoose population object or array)
interface IPaginateOptions {
limit: Number;
sortField: String;
sortAscending: Boolean;
next: String;
previous: String;
}
Response
The response object of findPaged()
is as follows:
interface IPaginateResult<T> {
hasNext: Boolean
hasPrevious: Boolean
next: String
previous: String
totalDocs: Number
docs: T[]
}
aggregatePaged()
aggregatePaged()
will return ordered and paged results based on a field (sortField
) that you pass in using MongoDB aggregate, which allows for more complicated queries compared to simple findPaged()
.
Parameters
Call aggregatePaged()
with the following parameters:
- options {IPaginateOptions} (The paginate options)
- _pipeline {PipelineStage[]} (The aggregation pipeline array)
Response
Same as for findPaged()
Typegoose Model
Create your typegoose model as follows:
import paginationPlugin, { PaginateModel } from 'typegoose-cursor-pagination';
import { prop, getModelForClass, plugin, index } from "@typegoose/typegoose";
import mongoose from "mongoose";
@plugin(paginationPlugin)
@index({ email: 1 })
export class User {
@prop({ required: true })
name: string;
@prop({ required: true })
email: string;
}
export const UserModel = getModelForClass(User, { existingMongoose: mongoose }) as PaginateModel<User, typeof User>;;
Example
Use the findPaged()
method as follows:
import { Request, Response, NextFunction } from "express";
import { IPaginateOptions } from "typegoose-cursor-pagination";
import UserModel from "./User";
export async function getUsers(req: Request, res: Response, next: NextFunction) {
const options: IPaginateOptions = {
sortField: "email",
sortAscending: true,
limit: 10,
next: "WyJuZXdAdG9rYXMubmwiLHsiJG9pZCI6IjVjNGYxY2U1ODAwYzNjNmIwOGVkZGY3ZCJ9XQ"
};
const query = {};
const projection = {};
const populate = []
const users = await UserModel.findPaged(options, query, projection, populate);
res.send(users)
}