Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda