Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
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();
    }
  }
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!