Implementing pagination in a Node.js application with MongoDB involves using the skip()
and limit()
methods provided by MongoDB queries. Additionally, you may need to keep track of the current page and the number of items per page. Here's a basic example using the mongoose
library, which is a popular MongoDB ODM (Object-Document Mapper) for Node.js:
bashnpm install mongoose
javascript// app.js
const mongoose = require('mongoose');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/your-database-name', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Create a mongoose model
const YourModel = mongoose.model('YourModel', {
// Define your schema here
// ...
});
javascript// app.js
const express = require('express');
const app = express();
const port = 3000;
const YourModel = require('./yourModel'); // Make sure to provide the correct path
app.get('/your-route', async (req, res) => {
const page = parseInt(req.query.page) || 1; // Current page, default is 1
const pageSize = parseInt(req.query.pageSize) || 10; // Number of items per page, default is 10
try {
// Calculate the skip value based on the page and pageSize
const skip = (page - 1) * pageSize;
// Fetch data with pagination using the skip and limit methods
const data = await YourModel.find()
.skip(skip)
.limit(pageSize);
res.json({
data,
page,
pageSize,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
In this example, the /your-route
endpoint accepts query parameters page
and pageSize
to implement pagination. The skip()
method is used to skip a certain number of documents, and the limit()
method is used to limit the number of documents returned.
You can make a request to /your-route?page=1&pageSize=10
to get the first page with 10 items, /your-route?page=2&pageSize=10
for the second page, and so on.
Remember to customize the code according to your schema and application requirements. Additionally, handle errors appropriately in a production environment.