Table of Contents
In this example, the related frameworks and templates used include: jade, mongoose, express, layui.
Entering the homepage for the first time:
The effect of clicking on the corresponding page:
Home Web Front-end JS Tutorial How to implement paging query in node

How to implement paging query in node

Oct 14, 2017 am 09:57 AM
node method Inquire


The jade template used at the front desk uses bootstrap layout and layui paging control.
index.jade main code:

//文章列表显示
     p.container      
     if(articals.length > 0)
       p.container.clear
        - for(var i=0;i<articals.length;i++)
         .col-lg-6.col-md-6.col-sm-12
          p.panel.panel-default
           .panel-heading
             a.block.bold(href = &#39;/details?id=#{articals[i]._id}&#39;)= articals[i].title
           p.panel-body.height50!= articals[i].detail
           p.panel-footer
            span.glyphicon.glyphicon-user(aria-hidden = "true")
            span(style = "margin-right:20px;margin-left:5px;")= articals[i].author
            span= articals[i].createDate       //添加分页
       p#pager.text-center.col-lg-12 col-md-12 col-sm-12
       .empty
       .empty
       script(type="text/javascript").
         layui.use([&#39;laypage&#39;, &#39;layer&#39;], function(){
          var laypage = layui.laypage;
          laypage.render({
            elem: &#39;pager&#39;
            ,count: #{total}
            ,curr:(&#39;#{page}&#39;||1)
            ,jump: function(obj, first){
              if(!first){
                window.location.href = &#39;/index/&#39;+obj.curr;
              }
            }
          });
         });      else
       h2 快去发表一篇文章吧~  #footer
       .container.text-center
            p 版权所有 &copy; 2017 LorettaXiongField
Copy after login

index.js main code:

var express = require(&#39;express&#39;);  
var mongoose = require(&#39;mongoose&#39;);require(&#39;../models/schema&#39;);var article = mongoose.model(&#39;Article&#39;);var user = mongoose.model(&#39;User&#39;);var url = require(&#39;url&#39;);var router = express.Router();  
//处理get请求router.get(&#39;/&#39;, function(req, res, next) {  
  var con = [];
  article.find({}).exec(function(err, doc){
    var total = doc.length;    //按时间顺序查找前10条文章的数据
    article.find({}).sort({createDate: -1}).populate(&#39;creator&#39;, &#39;name&#39;).limit(10).exec(function(err, character){
    //添加容错措施
        if(err){
          console.log(err);
        }else if(character.length == 0){        //没有任何文章,就直接返回
          console.log(&#39;no articles!&#39;);
          res.render(&#39;index&#39;, { 
            title: &#39;首页&#39;, 
            articals : con
          });  
        }else{          for(var i = 0; i < character.length; i++){
            con[i] = {
              _id: character[i]._id,
              title: character[i].title,
              detail: character[i].text.replace(/<[\/]{0,1}[a-zA-Z\s"&#39;=;]{1,}>/g, &#39;&#39;),
              author: character[i].creator.name,
              createDate: character[i].createDate
            };
          }          //返回文章总数以及前10条数据
          res.render(&#39;index&#39;, { 
            title: &#39;首页&#39;, 
            total: total,
            articals : con
          });  
        }
      });
  })
});   

//处理带有页码参数的get请求router.get(&#39;/index/:page&#39;, function(req, res, next) {  
  var con = [];  var pageNum = parseInt(req.params.page);  var Creator;  if(pageNum){
  article.find({}).exec(function(err, doc){
    var total = doc.length;    //按时间顺序查找从第[(页码-1)*10]条数据开始的10条文章的数据
    article.find({}).sort({createDate: -1}).populate(&#39;creator&#39;, &#39;name&#39;).skip((pageNum-1)*10).limit(10).exec(function(err, character){
    //添加容错措施
        if(err){
          console.log(err);
        }else if(character.length == 0){
          console.log(&#39;no articles!&#39;);
          res.render(&#39;index&#39;, { 
            title: &#39;首页&#39;, 
            articals : con
          });  
        }else{          for(var i = 0; i < character.length; i++){
            con[i] = {
              _id: character[i]._id,
              title: character[i].title,
              detail: character[i].text.replace(/<[\/]{0,1}[a-zA-Z\s"&#39;=;]{1,}>/g, &#39;&#39;),
              author: character[i].creator.name,
              createDate: character[i].createDate
            };
          }          //返回新的页码以及相应的10条数据
          res.render(&#39;index&#39;, { 
            title: &#39;首页&#39;, 
            total: total,
            page: pageNum,
            articals : con
          });  
        }
      });
   });
  }
});   

module.exports = router;
Copy after login

The main code of app.js is attached below: //Module dependency var express = require('express' );

var path = require(&#39;path&#39;);
    var logger = require(&#39;morgan&#39;);
    var http = require(&#39;http&#39;);
    var favicon = require(&#39;serve-favicon&#39;);
    var mongoose = require(&#39;mongoose&#39;);
    var bodyParser = require(&#39;body-parser&#39;);
    require(&#39;./models/schema&#39;);
    var user = mongoose.model(&#39;User&#39;);
    var cookieParser = require(&#39;cookie-parser&#39;);
    var session = require(&#39;express-session&#39;);
    var app = express();
    //日志设置app.use(logger(&#39;dev&#39;));
    //图标设置app.use(favicon(path.join(__dirname, &#39;public&#39;, &#39;favicon.ico&#39;)));
    //视图设置app.set(&#39;view engine&#39;, &#39;jade&#39;);
    app.set(&#39;views&#39;, path.join(__dirname, &#39;views&#39;));
    //静态文件设置app.use(express.static(path.join(__dirname, &#39;public&#39;)));
    //表单数据解析app.use(bodyParser.json());
    app.use(bodyParser.urlencoded( {
    extended: true }
));
    //路由设置var routes = require(&#39;./routes/index&#39;);
    app.use(&#39;/&#39;, routes);
    //服务器设置var server = app.listen(8081, function () {
    var host = server.address().address var port = server.address().port console.log(&#39;server start on 127.0.0.1:8081&#39;);
}
)
Copy after login

The following is the effect I achieved:

Entering the homepage for the first time:

How to implement paging query in node

The effect of clicking on the corresponding page:

How to implement paging query in node


The above is the detailed content of How to implement paging query in node. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to enter bios on Colorful motherboard? Teach you two methods How to enter bios on Colorful motherboard? Teach you two methods Mar 13, 2024 pm 06:01 PM

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

12306 How to check historical ticket purchase records How to check historical ticket purchase records 12306 How to check historical ticket purchase records How to check historical ticket purchase records Mar 28, 2024 pm 03:11 PM

Download the latest version of 12306 ticket booking app. It is a travel ticket purchasing software that everyone is very satisfied with. It is very convenient to go wherever you want. There are many ticket sources provided in the software. You only need to pass real-name authentication to purchase tickets online. All users You can easily buy travel tickets and air tickets and enjoy different discounts. You can also start booking reservations in advance to grab tickets. You can book hotels or special car transfers. With it, you can go where you want to go and buy tickets with one click. Traveling is simpler and more convenient, making everyone's travel experience more comfortable. Now the editor details it online Provides 12306 users with a way to view historical ticket purchase records. 1. Open Railway 12306, click My in the lower right corner, and click My Order 2. Click Paid on the order page. 3. On the paid page

How to check your academic qualifications on Xuexin.com How to check your academic qualifications on Xuexin.com Mar 28, 2024 pm 04:31 PM

How to check my academic qualifications on Xuexin.com? You can check your academic qualifications on Xuexin.com, but many users don’t know how to check their academic qualifications on Xuexin.com. Next, the editor brings you a graphic tutorial on how to check your academic qualifications on Xuexin.com. Interested users come and take a look! Xuexin.com usage tutorial: How to check your academic qualifications on Xuexin.com 1. Xuexin.com entrance: https://www.chsi.com.cn/ 2. Website query: Step 1: Click on the Xuexin.com address above to enter the homepage Click [Education Query]; Step 2: On the latest webpage, click [Query] as shown by the arrow in the figure below; Step 3: Then click [Login Academic Credit File] on the new page; Step 4: On the login page Enter the information and click [Login];

Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Mar 23, 2024 am 10:42 AM

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

See all articles