Sweet Way to Make Pagination With Mongodb

May 18, 2021tip slips

Make Pagination From DB Directly During Data Being Requested

I am too lazy to give the whole example, so I put only the query.

const page = 1 // this should be dynamically based on the request;
const itemPerPage = 10;
const startDate = moment().unix(); // get current time in unix timestamp

const post = await PostModel.find({ created: { $gt: startDate }})
                    .sort({ vote: -1, _id: -1 })
                    .skip((page - 1) * itemsPerPage)

The code above will return the array of post which is sorted by vote number and return only the suitable 10 first data depending on which page currenty the request is on.


.find({created: {$gt: startDate}})

This tells MongoDB that the query should only include items that were created in the past X time depending on startDate defined.

.sort({vote: -1, _id: -1})

This tells MongoDB to sort the items by their vote attribute in descending order. And we also use a secondary sort of _id, which will sort items based on their creation date.

.skip((page - 1) * itemsPerPage)

This tells MongoDB to paginate the results it gets from the database based on the current page number and the number of items we want to show per page (itemsPerPage). As we move beyond the first page of results, this method will help us skip the results that were shown on the pages before it.


The combination of the skip() and limit() methods is what creates the pagination of the results.


Thats it, Not sure if it super useful cause I just copy it from internet and it works for me and I find it very cool and super helpful. B)