猫鼬中的数据库查询有问题,我正在设置值,但没有得到正确的结果,不知道为什么,还想优化数据库查询。我使用mongoose来计算有多少记录与匹配的查询参数(分页(,我必须进行单独的查询。并且用CCD_ 1查找实际记录必须进行单独的查询。
但实际的问题是我试图获得的分页细节下面代码中的示例:如果我设置page
=1,page_size
=10,并且我的row_count
是3,那么我假设得到from
1和to
1,但我得到的是from
1和11
。
不确定我在这里做错了什么。
const pagination = async (model, query, page_number, page_size, order, order_by, next) => {
const pageS = parseInt(page_number)
let page = +pageS || 1;
const limit = parseInt(page_size)
let per_page = +page_size || 10;
if (page < 1) {
page = 1;
}
if (per_page < 1) {
per_page = 1;
}
const startIndex = (
page - 1
) * per_page;
const endIndex = page * page_size
const key = `${order}`
const results = {}
// here reading the data count from database
const resultCount = await model.countDocuments(query).exec();
if (endIndex < resultCount) {
results.next = {
page: page + 1,
page_size: limit
}
}
if (startIndex > 0) {
results.previous = {
page: page - 1,
page_size: limit
}
}
try {
// here trying to search the query with applied pagination
const data = await model.find(query)
.limit(per_page)
.skip(startIndex)
.sort({ [key] : order_by })
.exec()
// here I am passing details but not getting exact to and from; from is working expected but not to
// Example if I set page = 1, page_size = 10 and my row_count is 3 then I suppose to get from 1, and to 1 but intead I am getting from 1 and to 11.
const pagination_details = {
data: data,
meta: {
page,
page_size: per_page,
row_count: parseInt(resultCount, 10),
page_count: Math.ceil(resultCount / per_page ),
from:startIndex + 1,
to: endIndex + 1,
order: order,
order_by: order_by
}
}
return pagination_details
next()
} catch (e) {
console.log(e);
console.error(e);
}
};
有人能帮助我获得正确的数据吗?我在这里犯了什么错误。可能有逻辑错误
您忘记了用per_page除以起始索引和结束索引来获得页码,请尝试替换:
from:startIndex + 1,
to: endIndex + 1,
带有:
from: Math.floor(startIndex / per_page) + 1,
to: Math.ceil(endIndex / per_page) + 1,