Plugin: Pagination

Oli Lalonde edited this page Jun 6, 2017 · 4 revisions

Pagination Plugin

Similar to Model#fetchAll and Collection#fetch, but fetches a single page of results.


To use this plugin, simply call bookshelf.plugin('pagination')


Any options that may be passed to Model#fetchAll (such as withRelated) may also be passed in the options to fetchPage, as you can see in the example below.

To perform pagination, you must pass an options object with either page/pageSize or limit/offset keys. The following two calls are equivalent:

fetchPage({page: 10, pageSize: 20});
// OR
fetchPage({limit: 20, offset: 180});

By default, with no parameters or missing parameters, fetchPage will use an options object of {page: 1, pageSize: 10}

In the resulting pagination metadata, you will receive back the parameters used for pagination, i.e., either page/pageSize or offset/limit, respectively.

Below is an example showing the user of a JOIN query with sort/ordering, pagination, and related models.


Calling fetchPage

.query(function (qb) {
 qb.innerJoin('manufacturers', 'cars.manufacturer_id', '');
 qb.where('', '=', 'Sweden');
.orderBy('-productionYear') // Same as .orderBy('cars.productionYear', 'DESC')
 pageSize: 15, // Defaults to 10 if not specified
 page: 3, // Defaults to 1 if not specified

 // OR
 // limit: 15,
 // offset: 30,

 withRelated: ['engine'] // Passed to Model#fetchAll
.then(function (results) {
 console.log(results); // Paginated results object with metadata example below

Reading the pagination metadata

The fetchPage method attaches a pagination property to the resolved Collection instance.

 models: [<Car>], // Regular bookshelf Collection
 // other standard Collection attributes
 pagination: {
     rowCount: 53, // Total number of rows found for the query before pagination
     pageCount: 4, // Total number of pages of results
     page: 3, // The requested page number
     pageSize: 15, // The requested number of rows per page

     // OR, if limit/offset pagination is used instead of page/pageSize:
     // offset: 30, // The requested offset
     // limit: 15 // The requested limit
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.