What is the Purpose of a Website?
To display data and to interact with the data๐
But there are Hundreds of documents present in the Servers and handling or present all of them at once can become overwhelming for the Users.
This is where the concept of Pagination comes in.
APIs are designed in such a way that they provide results in the form of pages with a limited number of documents.
Since MongoDB is specialized in handling data in the form of JSON objects that APIs use, let's understand how to achieve this.
find()
Method
The find()
is a query method of MongoDB. It returns all or some documents based on the arguments passed inside the method.
But for simplicity let's just try to get all the data in the database.
limit()
Method
The limit()
method is another method of MongoDB. It accepts a number type argument, which specifies the number of documents to get in a particular query.
Let's say we want to have 15 documents in a single response object.
We can achieve this using the following code snippet :
db.posts.find().limit(15)
Now if we call this multiple times, we will always get the first 15 documents, but we do not want that.
skip()
Method
The skip()
method is also a method of MongoDB. It also accepts a number type argument, which specifies the number of documents to skip from the first document entry in a particular query.
We are getting 15 documents per query. So if we want the first page, we can use :
db.posts.find().limit(15).skip(0)
For the next page, we have to skip the first 15 documents, so we use :
db.posts.find().limit(15).skip(15)
And so on.
We see a pattern here: For page 1, we skip 15*(page_number - 1)
So if we have a endpoint that receives the page number, we can directly use this formula to create a paginated query :
app.get("/posts/page?",async (req,res)=>{
let pageNumber = req.params.page;
let data = await db.posts.find().limit(15).skip(15*(pageNumber-1));
res.send(data);
});
Hope you learnt something new.
You can also follow me on Instagram ๐ jsdecaf
Also connect with me on LinkedIn ๐ thevinitgupta
Do tell me in the comments if I was wrong somewhere!!๐๐
Top comments (0)