Created
July 29, 2021 08:37
-
-
Save waptik/9a1e275a34cfc5cad07e69e2faf4c68d to your computer and use it in GitHub Desktop.
Mongoose paginate typescript
This file contains hidden or 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
/** @see https://discord.com/channels/612400042900193311/612406252164612129/869681421567000608 **/ | |
export async function queryPaginate<T>( | |
model: ModelType<T>, | |
pageNum = 1, | |
filter: MongooseFilterQuery<DocumentType<T>>, | |
populate?: string[], | |
): Promise<IPaginatedData<T[]>> { | |
const [docs, total] = await Promise.all([ | |
model | |
.find(filter) | |
.sort({ createdAt: -1 }) | |
.limit(20) | |
.skip(pageNum === 1 ? 0 : (pageNum - 1) * 20) | |
.populate(populate) | |
.exec(), | |
model.countDocuments(filter).exec(), | |
]); | |
const totalPages = total > 0 ? Math.ceil(total / 20) || 1 : 0; | |
const nextPage = pageNum < totalPages ? pageNum + 1 : null; | |
return { | |
items: docs.map((e) => e.toJSON() as T), | |
total, | |
totalPages, | |
nextPage, | |
pageNumber: pageNum, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment