Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda