I have been learning to wonderful world of nest.js recently and I want to say it's actually very cool, in fact its fast becoming a favorite of mine to use when building backend.
A thing I struggled with this week was adding pagination into one of my functions that allowed me to switch through my documents. I tried many packages and none of them seemed to do it correct. So I went away and tried to find out the best way to do it and I needed it to be pretty simple.
Now before I begin I must say this is not a fully fledged Pagination and wont give you all the functions you would want in most cases. But what this will do is give a simple way to move between stacks of data and have a page count.
So we are using MongoDB and Nest.js and I am assuming you have this set up and you are ready to go.
So we have a entity set up and we have out Controllers and Services all sorted. So lets start with the controller.
@Get('get')
async getdata(@Query() {limit, skip}) {
return this.testService.getTests(
skip,
limit)
}
What we have above is a simple controller function that gives us a end point of '/get' and the returns the service passing in two params that are Skip and Limit. The skip and limit params are carried through the URL and the @Query picks those up.
/get?skip=8&limit=8
So lets head over to the service so we can see what we are doing here
async getTests(
skip = 0,
limit = 8,
) {
const count = await this.testModel.countDocuments({}).exec();
const page_total = Math.floor((count - 1)/ limit) + 1;
const data = await this.testModel.find().limit(limit).skip(skip).exec();
return {
data: data,
page_total: page_total,
status: 200,
}
}
Ok what we have here is the service taking the skip and limit and adding default values to them.
With the below line we count the documents and do some math to determine what the page count is.
const count = await this.testModel.countDocuments({}).exec();
const page_total = Math.floor((count - 1)/ limit) + 1;
Then we grab the data from the Mongo Database and pass our skip and limit to the find(). After all that we simple return our page totals and data.
Its a really simple way to have pagination and allows us to move through data.
Thanks for reading and have a fine Sunday!
Top comments (1)
I'm not sure this is efficient code & also why should you return status?)