goosepage is a super-easy pagination utility for mongoose cursors. ๐
goosepage is very unopinionated about the way you query. ๐ You can pass in any mongoose cursor. ๐ If you wanted to find blog posts for a specific author and paginate the results, you can do:
goosepage(BlogPost.find({ author: authorId }));
Let's say that you have a mongoose model BlogPost
whose collection contains over 50 documents. ๐ You want to display them in a paginated way:
$ npm i goosepage
var goosepage = require('goosepage');
goosepage(BlogPost.find())
.then((results) => console.log(results));
By default, this will query the first 20 items from page 0:
var results = {
// there are 52 documents in total for the query
total: 52,
// we are on page 0
page: 0,
// we queried 20 items per page
itemsPerPage: 20,
// the first 20 BlogPosts
items: [...]
}
You can customize the defaults by overriding:
goosepage.defaults = {
itemsPerPage: 20,
page: 0
};
If you want to query the second page, simply do:
goosepage(BlogPost.find(), { page: 1 })
.then((results) => console.log(results));
This will get you the next 20 items:
var results = {
total: 52,
page: 1, // this changed
itemsPerPage: 20,
items: [...] // this changed
}
For more or fewer items per page, you can always use opts.itemsPerPage
:
goosepage(BlogPost.find(), { itemsPerPage: 30 })
.then((results) => console.log(results));
This will get you the next 20 items:
var results = {
total: 52,
page: 0,
itemsPerPage: 30, // this changed
items: [...] // this changed
}
goosepage uses mongodb's skip()
and limit()
commands. ๐ This is not the fastest approach, even though it's fine for smaller datasets. ๐ If you are looking for a faster pagination solution, check out this article: Fast paging with MongoDB.