Last active
June 30, 2023 11:19
-
-
Save ivryb/fc5f1f633abdbddea0751b6e3925893e to your computer and use it in GitHub Desktop.
MongoDB Node driver Pagination
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
export const paginateMongoRequest = async (collection, params = {}) => { | |
const defaults = { | |
page: 1, | |
perPage: 18, | |
sort: undefined, | |
filter: undefined, | |
}; | |
const { page, perPage, sort, filter } = Object.assign(defaults, params); | |
const totalCount = await collection.countDocuments(filter); | |
const totalPages = Math.ceil(totalCount / perPage); | |
const items = await collection | |
.find(filter) | |
.sort(sort) | |
.limit(perPage) | |
.skip(perPage * (page - 1)) | |
.toArray(); | |
return { | |
page, | |
items, | |
totalPages, | |
}; | |
}; | |
// Usage example: | |
// import { MongoClient } from 'mongodb'; | |
// import { paginateMongoRequest } from './paginateMongoRequest.js'; | |
// const client = new MongoClient(MONGO_URL); | |
// const db = client.db(DB_NAME); | |
// await client.connect(); | |
// const documentsCollection = db.collection('documents'); | |
// const getAllDocuments = async (params) => { | |
// const page = params?.page ?? 1; | |
// const result = await paginateMongoRequest(documentsCollection, { | |
// page, | |
// sort: { createdAt: -1 }, // newest first | |
// filter: { | |
// email: { | |
// $ea: '[email protected]' // get all documents with email === [email protected] | |
// }, | |
// }, | |
// }); | |
// return result; // will return { items: [...], page: 1, totalPages: 123, } | |
// }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment