Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A bug with Nodejs Pagination

I’m trying to create this simple nodejs pagination with express and it works fine for all pages except the first page. When I get page 1 it keeps on loading without any result and idk whats the problem. Even youtube tutorials are writing the exact same code. Any help is appreciated

exports.paginatedResults = (model) => {
  return async (req, res, next) => {
    const page = parseInt(req.query.page)  || 1;
    const limit = req.query.limit * 1 || 100;
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    const results = {};
    if (endIndex < await model.countDocuments().exec()) {
      results.next = {
        page: page + 1,
        limit: limit,
      }
    }
    if (startIndex > 0) {
      results.previous = {
        page: page - 1,
        limit: limit,
      }
      results.results = await model.find().limit(limit).skip(startIndex).exec();
      res.paginatedResults = results;

      next();
    }
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

you have written model.find in if block which would not be executed for first page as startIndex would be 0 in that case. also you have written next() inside that if block so in case of first page it would not be getting called that is why the page is in loading state.

try like this

exports.paginatedResults = (model) => {
  return async (req, res, next) => {
    const page = parseInt(req.query.page)  || 1;
    const limit = req.query.limit * 1 || 100;
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    const results = {};
    if (endIndex < await model.countDocuments().exec()) {
      results.next = {
        page: page + 1,
        limit: limit,
      }
    }
    if (startIndex > 0) {
      results.previous = {
        page: page - 1,
        limit: limit,
      }
     }
    results.results = await model.find().skip(startIndex).limit(limit).exec();
      res.paginatedResults = results;

      next();
  }
}

also you should use skip first then add limit.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading