index:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {margin:0; padding: 0;}
li {list-style: none;}
body {background: #eee;}
.wrapper {background: #fff;width: 970px; margin:20px auto; padding: 15px;}
h1 {text-align: center; border-bottom: 1px solid #ddd; padding-bottom: 20px;}
li {margin:20px 0; border-bottom: 1px dotted #eee; padding-bottom: 20px;}
p { line-height: 25px;}
</style>
</head>
<body>
<div class="wrapper">
<h1>新闻列表(传统分页)<script>document.write(new Date().toLocaleString())</script></h1>
<ul>
<% news.forEach(item=>{ %>
<li>
<h2><a href="#"><%= item.title %></a></h2>
<p class="time"><%= item.time %></p>
<p class="summary"><%= item.summary %></p>
</li>
<% }) %>
</ul>
<div class="footer">
//“?”表示查询数据
<p>总共有<%= total %>条新闻,每页显示<%= pageSize %>条,当前是<%= page %>/<%= size %>页
<% if(page == 1){ %>
上一页
<% }else{ %>
<a href="?page=<%= page*1 - 1 %>">上一页</a>
<% } %>
<% if(page == size){ %>
下一页
<% }else{ %>
<a href="?page=<%= page*1 + 1 %>">下一页</a>
<% } %>
</p>
</div>
</div>
</body>
# JS:
let express = require("express");
let path = require("path");
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
let app = express();
app.get("/",(req,res)=>{
let page = req.query.page || 1;
(page <= 0) && (page = 1)
let pageSize = 3;
let offset = (page-1)*pageSize;
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("news");
dbo.collection("newslist").find({}).skip(offset).limit(pageSize).toArray(function(err, result) {
if (err) throw err;
dbo.collection("newslist").count().then(result2=>{
let total = result2;
let size = Math.ceil(total / pageSize)
res.render(path.resolve(__dirname,"./views/index.ejs"),{
news:result,
total,
pageSize,
page,
size,
})
});
db.close();
});
});
})
app.listen(3000,()=>{
console.log("3000 ok~")
})