The Ultimate Guide to Mongoose Paginate Boost Your MongoDB Query Efficiency

Introduction to mongoose-paginate

Mongoose-paginate is a powerful plugin for Mongoose that simplifies adding pagination to your MongoDB queries. It is very useful when dealing with large datasets where you need to load data in chunks or pages to improve performance and user experience.

Setting Up mongoose-paginate

 // Installation via npm npm install mongoose-paginate-v2 

Adding Pagination to a Mongoose Model

 const mongoose = require('mongoose'); const mongoosePaginate = require('mongoose-paginate-v2');
const schema = new mongoose.Schema({
  title: String,
  content: String
});
schema.plugin(mongoosePaginate);
const Post = mongoose.model('Post', schema); 

Using the paginate Method

 // Paginate through posts Post.paginate({}, { page: 1, limit: 10 }, function(err, result) {
  // Result contains docs, totalDocs, limit, totalPages, page, and more
}); 

Query with Options

 const options = {
  page: 1,
  limit: 5,
  sort: { title: 1 },
  select: 'title'
};
Post.paginate({}, options, function(err, result) {
  // Handle results
}); 

Mongoose Paginate with Aggregation

 const aggregateQuery = Post.aggregate([
  { $match: { title: { $regex: '.*sample.*' } } },
  { $sort: { title: 1 } }
]);
const options = {
  page: 1,
  limit: 5
};
Post.aggregatePaginate(aggregateQuery, options, function(err, result) {
  // Handle results
}); 

Advanced Pagination Example

Let’s create a simple application to demonstrate the usage of mongoose-paginate in a full-stack application:

Backend (Express App)

 const express = require('express'); const mongoose = require('mongoose'); const mongoosePaginate = require('mongoose-paginate-v2');
const app = express(); const port = 3000;
mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true, useUnifiedTopology: true });
const postSchema = new mongoose.Schema({
  title: String,
  content: String
});
postSchema.plugin(mongoosePaginate); const Post = mongoose.model('Post', postSchema);
app.get('/posts', (req, res) => {
  const { page, limit } = req.query;
  const options = {
    page: parseInt(page, 10) || 1,
    limit: parseInt(limit, 10) || 10
  };
  
  Post.paginate({}, options, (err, result) => {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    res.json(result);
  });
});
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
}); 

Frontend (React Component)

 import React, { useEffect, useState } from 'react'; import axios from 'axios';
const Posts = () => {
  const [posts, setPosts] = useState([]);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  useEffect(() => {
    const fetchPosts = async () => {
      const response = await axios.get(`/posts?page=${page}&limit=5`);
      setPosts(response.data.docs);
      setTotalPages(response.data.totalPages);
    };

    fetchPosts();
  }, [page]);

  return (
    

Posts

    {posts.map(post => (
  • {post.title}
  • ))}
{[...Array(totalPages)].map((_, idx) => ( ))}
); }; export default Posts;

By following these steps, you can effectively implement pagination in your Mongoose models and improve your application’s efficiency and user experience.

Hash: 2cef239f0d9ab110bfafa1fd30fa6550e43393cf97163c6810167a1d98320ff6

Leave a Reply

Your email address will not be published. Required fields are marked *