B
B
BEKa T2019-08-16 10:08:24
MongoDB
BEKa T, 2019-08-16 10:08:24

How to implement pagination in NodeJS?

I have a posts table with the author field, so that when you go to users/username/{page number}, the author's posts are displayed in the template.
Like this, but here pagination of posts of all users

const express = require('express');
const router = express.Router();

const config = require('../config');
const models = require('../models');

function posts(req, res) {
  const userId = req.session.userId;
  const userLogin = req.session.userLogin;
  const perPage = +config.PER_PAGE;
  const page = req.params.page || 1;

  models.Post.find({}).skip(perPage * page - perPage)
  .limit(perPage)
  .then(posts => {
    models.Post.countDocuments().then(count => {
      res.render('index', {
        posts,
        current: page,
        pages: Math.ceil(count / perPage),
        user: {
          id: userId,
          login: userLogin
        }
      });
    }).catch(() => {
      throw new Error('Server dead :)')
    });
  }).catch(() => {
      throw new Error('Server dead :)')
    });
}

// Main view
router.get('/', (req, res) => posts(req, res));
router.get('/archive/:page', (req, res) => posts(req, res));

router.get('/posts/:post', (req, res, next) => {
  const url = req.params.post.trim().replace(/ +(?= )/g, '');
  const userId = req.session.userId;
  const userLogin = req.session.userLogin;

  if (!url) {
    const err = new Error('Not Found');
    err.status = 404;
    next(err);
  } else {
    models.Post.findOne({
      url
    }).then(post => {
      if (!post) {
        const err = new Error('Not Found');
        err.status = 404;
        next(err);
      } else {
        res.render('post/post', {
          post,
          user: {
            id: userId,
            login: userLogin
          }
        });
      }
    })
  }
});

module.exports = router;

Sample
<!-- Posts { -->
    </div>
    <div class="col-md-8 order-md-1">

      <% for (var i = 0; i < posts.length; i++) { %>
        <div class="card mb-2" style="">
          <div class="card-body">
            <h5 class="card-title"><a href="/posts/<%= posts[i].url %>"><%= posts[i].title %></a></h5>
            <p class="card-text"><%= posts[i].body %></p>
            <h6 class="card-subtitle mb-2 text-muted"><b>Создано: </b><%= posts[i].createdAt %><br><b>Обновлено: </b><%= posts[i].updatedAt %></h6>
            <span>
              Автор:<a href="#" class="card-link"> <%= posts[i].author %></a>
            </span>
            <a href="#" class="card-link float-right">Комментарии</a>
          </div>
        </div>
      <% } %>

  <!-- Pagination { -->

      <div class="pagination m-5">
        <!-- Home -->
        <% if (current == 2) { %>
          <a class="new" href="/">&#9751 Главная</a>
        <% } %>
        <!-- Right -->
        <% if (current > 2) { %>
          <a class="new" href="/archive/<%= Number(current) - 1 %>">&#10096 Вперед</a>
        <% } %>
        <!-- Back -->
        <% if (pages > 0 && current < pages ) { %>
          <a class="old ml-auto" href="/archive/<%= Number(current) + 1 %>">Назад &#10097</a>
        <% } %>
      </div>
  <!-- } -->

    </div>
<!-- } -->

How can this be implemented?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question