mongoose, ajax, express, pagination plug-ins to achieve paging effect

1. Download pagination plug-in first. Download address: JQuery paging plug-in

2. After downloading, add in the page, including CSS and JS files: the HTML part and JS part are as follows

<link rel="stylesheet" href="/public/css/pagination.css"/>

<div class="page">
    <div class="m-style M-box11"></div>
</div>
//Introducing plug-ins
<script src="/public/js/jquery-3.4.1.min.js"></script>
<script src="/public/js/jquery.pagination.js"></script>
<script>
     $('.M-box11').pagination({
         mode: 'fixed'
      });
</script>

After completing the above operations, you can see the paging button effect on the page. Of course, there are several paging buttons in the paging plug-in, which you can select according to your own needs.

3. We know that there is a syntax in mongoose, which can help us to complete the paging effect very quickly, that is, Model.skip(num1).limit(num2)... This statement means to skip num1 data and get num2 data. For example, we display 8 data on one page, and we want to get 8 data on the third page, so we can write it as Model.skip(2*8).limit(8).exec(...). With this method, it is very convenient for us. Now, what we need to do is to pass the two parameters of page number and how many pieces of data are displayed on one page to the background. The background will go to the database to obtain the corresponding data according to the above methods.

4. According to the paging plug-in, get two parameters (pageNum: page number, pageSize: page number). We update the code in the JS section as follows:

<script type="text/javascript">
		
$('.M-box11').pagination({
	mode: 'fixed',
	totalData: 20, //The total number of data. The total number needs to be acquired in the background to get {{count}}}. Here, for the convenience of displaying and using numbers directly.
	showData: 8, //Number of entries per page
	pageCount: {{count%showData==0?count/showData:count/showData+1}}, //PageCount
	callback:function(api){ //The callback function is called when the user clicks the page number
		var currentNum = api.getCurrent() //Current page number
		getList(currentNum,this.showData) //Take the current page number and the number of bars displayed per page as parameters
	}
},function(){ //This function is executed when the page is loaded
	getList(1,8) //When the page is loaded, 8 pieces of data on the first page will be displayed first
});
		
function getList(pageNum,pageSize){
	$.ajax({
		url:'/article/'+pageNum+'/'+pageSize,
		dataType:"JSON",
		success:function(result){  //Accept data returned by background
                var aa =""
		    for(var i = 0 ;i<result.articleList.length;i++){
			    var $value = result.articleList[i]
			    var $time = new Date(new Date($value.add_time) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '') //Format time
			aa+=`
			<li class="article-item">
				<a href="/article/detail?id=`+$value._id.toString()+`">
					<h2 class="p-title">`+$value.title+`</h2>
					<p class="p-abbr"> `+ $value.content.replace(/<\/?[^>]*>/g,'')+`</p>
					<div class="p-info clearfix">
						<p class="fl">
							<span class="time">Time:`+ $time +`</span>
						</p>
						<p class="fr">
							<span class="click">Views:`+$value.visit+`</span>
						</p>
					</div>
				</a>
			</li>`
			}
				$("#articleUl").html(aa) / / add the html code aa to the page to display
			  }
			})
		}
	</script>

5. In the above code, the url of Ajax request is' / article/'+pageNum+'/'+pageSize. I accept such request in the background, which is built by express framework. The code in router.js is as follows:

router.get('/article/:pageNum/:pageSize', function(req,res){
    const pageNum = parseInt(req.params.pageNum)
	const pageSize = parseInt(req.params.pageSize)
	Article.findAll(pageNum,pageSize,function(err,data){
		if(err){
			return res.status(500).send('Server error.')
		}else{
				res.send({
					articleList: data,
				})
			}
		})
	})
})

6. findAll in the above code is a method encapsulated by myself. In the schema definition of Article, add a static method for it, as follows

// Query article paging query
articleSchema.static('findAll',function(pageNum,pageSize,callback){
    this.find()
	.sort({add_time:-1}) //Sort by data
	.skip((pageNum-1)*pageSize)
	.limit(pageSize) //If the number of remaining articles on the last page is less than the number of pageSize, only the remaining ones will be displayed and no error will be reported.
    .exec(function(err, ret){
        callback(err,ret)
    })
})

In this way, we use mongoose, express, ajax to complete the paging function.

——————- this is the dividing line. The paging function has been completed above. Other methods are as follows -——————————

Other considerations:

After the ajax request, we get the data returned by the background in success: you can use the art template template to update the data on the page, rather than using strings to splice into html code.

$.ajax({
	url:'/article/'+pageNum+'/'+pageSize,
	dataType:"JSON",
	success:function(result){
	    var json = { 
		    articleList2: result.articleList,
	    };
	    var aa = template('tmp', json);
        $("#articleUl").html(aa)
})
<script src="/node_modules/art-template/lib/template-web.js">
<script id="tmp" type="text/art-template">
	<div>
	{{each articleList2}}
	<li class="article-item">
		<a href="/article/detail?id={{$value._id.toString()}}">
			<h2 class="p-title"><i class="iconfont icon-wenzhang_huaban" style="color: #5555ff;"></i>{{$value.title}}</h2>
			<p class="p-abbr"> {{$value.content.replace(/<\/?[^>]*>/g,'')}} </p>
		</a>
	</li>
	{{ /each }}
</div>
</script>

After the introduction of art template template engine, we can use the above method to complete. I think this method is better. But after I introduce the art template.js file alone, the template engine does not take effect, and I haven't found out the problem. Is it because I introduced express art template in the project, and now I introduce art template.js alone? Still thinking....

74 original articles published, 28 praised, 120000 visitors+
Private letter follow

Tags: JSON JQuery Mongoose Database

Posted on Sun, 01 Mar 2020 22:21:07 -0500 by ksmatthews