Nodejs Pagination

杀马特。学长 韩版系。学妹 提交于 2020-08-11 00:14:09

问题


I want to make a pagination with Nodejs and Mongoose. I can limit the posts but I couldn't handle the connection of front-end to back-end.

this is app.js:

app.get('/', function (req, res) {
  var perPage = 2
  var page = req.params.page || 1

  Metin
  .find({})
  .skip((perPage * page) - perPage)
  .limit(perPage)
  .exec(function(err, metins) {
      Metin.count().exec(function(err, count) {
          if (err) return next(err)
          res.render('index', {
              metins: metins,
              current: page,
              pages: Math.ceil(count / perPage)
          })
      })
  })
});

And this is my index.pug

extends layout

block content
  body
    br 
    br
    br
    .container
      ul.list-group
        each metin, i in metins
          li.list-group-item
            a(href="/metin/" + metin._id)= metin.baslik

I want to add buttons that can pass to related paginated webpage. Can you please help me?

Something like below this line can be solution ?

a(href='?page=' + pages)= length.pages.

回答1:


You can use while iterator to loop over the pages variable to make a number for each of your pages. And conditionally show/hide Previous/Next links based on current variable. This should work if you don't have a large amount of pages:

ul
  if current > 1
    li
      a(href=`?page=${parseInt(current) - 1}`) Previous
  - var i = 1
  while i <= pages
    li
      a(href=`?page=${i}`)= i++
  if current < pages
    li
      a(href=`?page=${parseInt(current) + 1}`) Next

Additionally, see this example.



来源:https://stackoverflow.com/questions/61838202/nodejs-pagination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!