Home > Software design >  A bug with Nodejs Pagination
A bug with Nodejs Pagination

Time:04-08

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();
    }
  }
}

CodePudding user response:

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.

  • Related