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

196
Vistas
Node JS - Simple Pagination - How to use Middleware in the route?

I'm new to Node and Express. I am currently adding a pagination function to my API. Most of the hard work is done so far, but I can't make it work since I've refactored and made the pagination a function.

Here is my route:

const projects = require('../controllers/project.controller');

module.exports = (app) => {
  var router = require('express').Router();
  // Retrieve all project
  router.get('/', projects.findAll);
};

Here is the middleware:

const paginatedResults = (model) => {
  return (req, res, next) => {
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;

    const results = {};
    if (endIndex < model.length) {
      results.next = {
        page: page + 1,
        limit: limit,
      };
    }
    if (startIndex > 0) {
      results.previous = {
        page: page - 1,
        limit: limit,
      };
    }
    results.results = model.slice(startIndex, endIndex);
    res.paginatedResults = results;
    next();
  };
};

const pagination = {
  paginatedResults,
};

module.exports = pagination;

Here is my controller:

exports.findAll = (req, res) => {
  Project.find({}, (err, data) => {
    res.send(data);
  });
};

I'm just wondering is there something I should change within the function? Ideally I'd like to be able to use in the route (e.g. router.get('/', [pagination.paginatedResults(Projects), projects.findAll]))

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

middlewares work one by one. You try to paginate when you have no results to paginate. If you are fine with using helper function, Try something like this.

//route
const projects = require('../controllers/project.controller');

module.exports = (app) => {
  var router = require('express').Router();
  // Retrieve all project
  router.get('/', projects.findAll);
};


// controller
exports.findAll = (req, res) => {
  const mongoQuery = Project.find();
  const result = await paginateQuery(mongoQuery, req.query.page, req.query.limit);
  res.send(result)
};

// helper
const paginateQuery =async (mongoQuery, page, limit) => {
  const skip = page-1
  const  results =await mongoQuery.skip(skip).limit(limt)
  // transform results the way you want and/or build response object
  return results

};
about 4 years ago · Juan Pablo Isaza 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