Pagination is a useful feature that often used in data presentation. It allows data to be split into multiple pages, and it will only retrieve a certain amount of data at one time. This can reduce loading times and make apps with large amounts of data much more pleasant to use.
Here is a basic example of how to implement pagination in Node.js using a MongoDB database and the Mongoose ODM:
1. Setup mongoose
```
const mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost/mongo-pagination’)
.then(() => console.log(‘MongoDB Connected…’))
.catch(err => console.log(err));
```
1. Define a schema and model
```
const userSchema = mongoose.Schema({
name: String,
email: String
});
const User = mongoose.model(‘Users’, userSchema);
```
1. Server and route setup
```
const express = require(‘express’);
const app = express();
app.get(‘/users’, paginatedResults(User), (req, res) => {
res.json(res.paginatedResults);
});
const PORT = 3400;
app.listen(PORT, () => console.log(`Server is running on PORT ${PORT}`));
```
1. Pagination middleware
```
function paginatedResults(model) {
return async (req, res, next) => {
const page = parseInt(req.query.page);
const limit = parseInt(req.query.limit);
const startIndex = (page – 1) * limit;
const endIndex = page * limit;
const results = {};
With this setup, you can now use query parameters in your API to specify the page number and the number of items per page.
For example:
- http://localhost:3400/users?page=3&limit=10
The page starts at 1 and the limit is the number of items you want to display on one page. The response will include the `next` and `previous` pages.
Note: This code assumes that you already have an express server setup and a MongoDB database. It is also a simplified example and does not include things like error handling. Make sure to tailor the code above to fit your own needs.