Created
November 24, 2021 10:05
-
-
Save OtayNacef/c8dfda956d214fe2b3e7b1b6e447548d to your computer and use it in GitHub Desktop.
Pagination Pipeline Using Aggregate - Mongoose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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