node-blog/utils/pagination.js
2025-06-24 11:42:12 +08:00

81 lines
2.1 KiB
JavaScript

/**
* 分页工具函数
*/
/**
* 计算分页信息
* @param {number} total - 总记录数
* @param {number} page - 当前页码
* @param {number} limit - 每页记录数
* @returns {object} 分页信息对象
*/
function getPaginationInfo(total, page = 1, limit = 10) {
const totalPages = Math.ceil(total / limit);
const currentPage = Math.max(1, Math.min(page, totalPages));
const skip = (currentPage - 1) * limit;
return {
currentPage,
totalPages,
limit,
skip,
total,
hasNext: currentPage < totalPages,
hasPrev: currentPage > 1
};
}
/**
* 为MongoDB查询添加分页
* @param {object} query - MongoDB查询对象
* @param {number} page - 当前页码
* @param {number} limit - 每页记录数
* @returns {object} 包含分页信息的查询对象
*/
function addPaginationToQuery(query, page = 1, limit = 10) {
const paginationInfo = getPaginationInfo(query.total || 0, page, limit);
return {
...query,
skip: paginationInfo.skip,
limit: paginationInfo.limit,
pagination: paginationInfo
};
}
/**
* 执行分页查询
* @param {object} model - Mongoose模型
* @param {object} filter - 查询条件
* @param {object} options - 查询选项
* @param {number} page - 当前页码
* @param {number} limit - 每页记录数
* @returns {Promise<object>} 包含数据和分页信息的对象
*/
async function paginateQuery(model, filter = {}, options = {}, page = 1, limit = 10) {
const paginationInfo = getPaginationInfo(0, page, limit);
// 获取总记录数
const total = await model.countDocuments(filter);
// 更新分页信息
const updatedPagination = getPaginationInfo(total, page, limit);
// 执行查询
const data = await model.find(filter, null, {
...options,
skip: updatedPagination.skip,
limit: updatedPagination.limit
});
return {
data,
pagination: updatedPagination
};
}
module.exports = {
getPaginationInfo,
addPaginationToQuery,
paginateQuery
};