下面给出“NodeJs操作MongoDB教程之分页功能以及常见问题”的完整攻略:
一、前言
在进行分页操作之前,需要先在 MongoDB 数据库中存入一些数据,可以使用如下示例代码:
// index.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/pagination-demo', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('Database connected successfully');
});
const articleSchema = new mongoose.Schema({
title: String,
content: String,
created: { type: Date, default: Date.now }
});
const Article = mongoose.model('Article', articleSchema);
const articles = [
{ title: 'Article 1', content: 'Content for Article 1' },
{ title: 'Article 2', content: 'Content for Article 2' },
{ title: 'Article 3', content: 'Content for Article 3' },
{ title: 'Article 4', content: 'Content for Article 4' },
{ title: 'Article 5', content: 'Content for Article 5' },
{ title: 'Article 6', content: 'Content for Article 6' },
{ title: 'Article 7', content: 'Content for Article 7' },
{ title: 'Article 8', content: 'Content for Article 8' },
{ title: 'Article 9', content: 'Content for Article 9' },
{ title: 'Article 10', content: 'Content for Article 10' },
];
Article.insertMany(articles).then(() => {
console.log('Data added successfully');
});
二、分页查询
1. 普通分页
在进行分页查询之前,先安装 MongoDB 的驱动程序 mongoose:
npm install mongoose
使用 mongoose 实现分页查询时可以使用如下的代码:
// pagination.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/pagination-demo', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('Database connected successfully');
});
const articleSchema = new mongoose.Schema({
title: String,
content: String,
created: { type: Date, default: Date.now }
});
const Article = mongoose.model('Article', articleSchema);
async function getArticles(pageNumber, pageSize) {
const count = await Article.countDocuments();
const articles = await Article.find()
.skip((pageNumber - 1) * pageSize)
.limit(pageSize)
.exec();
return {
totalPage: Math.ceil(count / pageSize),
articles,
};
}
getArticles(2, 4).then(data => {
console.log(data);
});
2. 前端分页
如果希望在前端进行分页,可以将所有的数据查询出来,然后再根据当前页码和每页显示条数计算要显示的数据:
// pagination.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/pagination-demo', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('Database connected successfully');
});
const articleSchema = new mongoose.Schema({
title: String,
content: String,
created: { type: Date, default: Date.now }
});
const Article = mongoose.model('Article', articleSchema);
async function getArticles() {
const articles = await Article.find().exec();
return {
articles,
};
}
getArticles().then(data => {
console.log(data);
});
然后在前端进行渲染和分页处理。
三、常见问题
1. 数据量太大怎么办?
答:可以使用游标来实现,并且每次取出一部分数据进行渲染,这样可以避免一次性查询出大量数据,造成服务器压力过大的情况。
2. 怎样进行排序?
答:可以使用 mongoose 的 sort 方法来进行排序,示例代码如下:
async function getArticles(pageNumber, pageSize) {
const count = await Article.countDocuments();
const articles = await Article.find()
.sort({ created: -1 })
.skip((pageNumber - 1) * pageSize)
.limit(pageSize)
.exec();
return {
totalPage: Math.ceil(count / pageSize),
articles,
};
}
getArticles(2, 4).then(data => {
console.log(data);
});
其中 sort({ created: -1 })
表示按照创建时间进行倒序排序。
四、示例说明
假设现在需要在前端进行分页显示文章列表,每页显示 4 条数据,用户可以选择查看不同页码的内容,可以按照创建时间进行倒序排序。
我们可以使用如下示例代码来实现:
// pagination.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/pagination-demo', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('Database connected successfully');
});
const articleSchema = new mongoose.Schema({
title: String,
content: String,
created: { type: Date, default: Date.now }
});
const Article = mongoose.model('Article', articleSchema);
async function getArticles(query, pageNumber, pageSize) {
const count = await Article.countDocuments(query);
const articles = await Article.find(query)
.sort({ created: -1 })
.skip((pageNumber - 1) * pageSize)
.limit(pageSize)
.exec();
return {
totalPage: Math.ceil(count / pageSize),
articles,
};
}
module.exports = { getArticles };
然后在前端代码中调用该方法:
// index.js
import { getArticles } from './pagination';
const pageContainer = document.querySelector('.page-container');
const pagePrevious = document.querySelector('.page-previous');
const pageNext = document.querySelector('.page-next');
let currentPage = 1;
let currentQuery = {};
function renderPage(data) {
const totalPages = data.totalPage;
const articles = data.articles;
// 渲染文章列表
// ...
// 渲染页码
// ...
// 重置分页按钮状态
if (currentPage === 1) {
pagePrevious.disabled = true;
} else {
pagePrevious.disabled = false;
}
if (currentPage === totalPages) {
pageNext.disabled = true;
} else {
pageNext.disabled = false;
}
}
async function fetchData() {
const data = await getArticles(currentQuery, currentPage, 4);
renderPage(data);
}
fetchData();
pagePrevious.addEventListener('click', () => {
if (currentPage === 1) {
return;
}
currentPage--;
fetchData();
});
pageNext.addEventListener('click', () => {
const totalPages = pageContainer.querySelectorAll('.page').length;
if (currentPage === totalPages) {
return;
}
currentPage++;
fetchData();
});
在上面的示例代码中,getArticles
方法接收一个查询条件、页码和每页显示的数量,然后返回符合条件的文章列表和分页信息。在前端代码中,分别监听上一页和下一页按钮的点击事件,然后根据当前页码和总页数计算要显示的数据。在渲染完数据之后,还要根据当前页码和总页数来决定上一页和下一页按钮是否可用。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:NodeJs操作MongoDB教程之分页功能以及常见问题 - Python技术站