Skip to content

Instantly share code, notes, and snippets.

@OtayNacef
Created November 24, 2021 10:05
Show Gist options
  • Save OtayNacef/c8dfda956d214fe2b3e7b1b6e447548d to your computer and use it in GitHub Desktop.
Save OtayNacef/c8dfda956d214fe2b3e7b1b6e447548d to your computer and use it in GitHub Desktop.
Pagination Pipeline Using Aggregate - Mongoose
export const paginationAggregate = ( page: number) => {
//Max Items
const limit = 10;
const skip = (page - 1) * limit;
return [
{
$unwind: '$total',
},
{
$project: {
items: {
$slice: [
'$data',
skip,
{
$ifNull: [limit, '$total.count'],
},
],
},
page: {
$literal: skip / limit + 1,
},
hasNextPage: {
$lt: [{ $multiply: [limit, Number(page)] }, '$total.count'],
},
totalPages: {
$ceil: {
$divide: ['$total.count', limit],
},
},
totalItems: '$total.count',
},
},
];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment