B
B
BEKa T2019-08-14 11:22:01
MongoDB
BEKa T, 2019-08-14 11:22:01

Pagination error in NodeJS?

In the console, display such an error when trying to view user's posts (when you click on the "Back (view user's old posts)" button)

[nodemon] starting `node app.js`
Example app listening on port 3000!
Data base connected
(node:7033) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of null
    at /home/bred/Рабочий стол/Папка/Blog/routes/archive.js:83:17
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:7033) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7033) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:7033) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of null
    at /home/bred/Рабочий стол/Папка/Blog/routes/archive.js:83:17
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:7033) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:7033) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of null
    at /home/bred/Рабочий стол/Папка/Blog/routes/archive.js:83:17
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:7033) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
(node:7033) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of null
    at /home/bred/Рабочий стол/Папка/Blog/routes/archive.js:83:17
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:7033) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)

5d51a26fcca25464104849.png
<!-- 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="/users/<%=_user.login %>/<%= Number(current) + 1 %>">Назад &#10097</a>
        <% } %>
      </div>
<!-- } -->

archive.js
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)
  .populate('author')
  .sort({ createdAt: -1 })
  .then(posts => {
    models.Post.countDocuments().then(count => {
      res.render('archive/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
          }
        });
      }
    })
  }
});

//users posts
router.get('/users/:login/:page*?', (req, res) => {
  const userId = req.session.userId;
  const userLogin = req.session.userLogin;
  const perPage = +config.PER_PAGE;
  const page = req.params.page || 1;
  const login = req.params.login;

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

  
});

module.exports = router;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BEKa T, 2019-08-18
@Bread09

models.Post.find({
      author: <b>user</b>
    })
    .skip(perPage * page - perPage)
    .limit(perPage)
    .sort({ createdAt: -1 })
    .then(posts => {
      models.Post.countDocuments({
        author: <b>user</b>
      })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question