Skip to content

Instantly share code, notes, and snippets.

@toluolatubosun
Last active September 16, 2022 21:21
Show Gist options
  • Save toluolatubosun/cc4f51c4d21fd7ae47b26b004feb6ed9 to your computer and use it in GitHub Desktop.
Save toluolatubosun/cc4f51c4d21fd7ae47b26b004feb6ed9 to your computer and use it in GitHub Desktop.
This is an Implementation of cursor pagination using Typescript and Mongoose
async getAll(pagination: PaginationInput) {
/* Note:
* - if sorting in descending order then use $lt
* - if sorting in ascending order then use $gt
*/
const { limit = 5, next } = pagination;
var query = {};
const total = await User.countDocuments(query);
if (next) {
const [nextId, nextCreatedAt] = next.split("_");
query = {
...query,
$or: [
{ createdAt: { $gt: nextCreatedAt } },
{ createdAt: nextCreatedAt, _id: { $gt: nextId } }
]
};
}
const users = await User.find(query, { password: 0, __v: 0 })
.sort({ createdAt: 1, _id: 1 })
.limit(Number(limit) + 1);
const hasNext = users.length > limit;
if (hasNext) users.pop(); // Remove the extra user from the array
const nextCursor = hasNext ? `${users[users.length - 1]._id}_${users[users.length - 1].createdAt.getTime()}` : null;
return {
users,
pagination: {
total,
hasNext,
next: nextCursor
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment