[英]Pagination in node js with mongo db
function getDigitalMigrationJoin(req, res, next) {
DigitalMigrationForm.aggregate([
// Join with user_info table
{
$lookup: {
from: DigitalMigrationFormList.collection.name, // other table name
localField: "_id", // name of users table field
foreignField: "digitalFormId", // name of userinfo table field
as: "forms" // alias for userinfo table
}
},
]).exec(function (err, results) {
console.log(results)
res.send(results)
})
}
我想在這個 function 上添加分頁限制和頁面請幫助我
要添加分頁,您可以在aggregate
方法中使用$skip
和$limit
。
$skip
跳過特定數量的文檔; $limit
限制傳遞到管道中下一階段的文檔數量。
他是你的function的升級版:
const getDigitalMigrationJoin = (req, res, next) => {
// Extract page and pageSize parameters from the request query
const page = req.query.page || 1;
const pageSize = req.query.pageSize || 10;
// Calculate skip and limit values based on the page and pageSize
const skip = (page - 1) * pageSize;
const limit = pageSize;
DigitalMigrationForm.aggregate([
// Join with user_info table
{
$lookup: {
from: DigitalMigrationFormList.collection.name, // other table name
localField: "_id", // name of users table field
foreignField: "digitalFormId", // name of userinfo table field
as: "forms" // alias for userinfo table
}
},
// Skip a specified number of documents
{ $skip: skip },
// Limit the number of documents passed to the next stage
{ $limit: limit }
]).exec(function (err, results) {
console.log(results)
res.send(results)
})
}
你可以這樣做:
const page = req.query.page || 1;
const pageSize = req.query.pageSize || 10;
DigitalMigrationForm.aggregate([
{
$lookup: {
from: DigitalMigrationFormList.collection.name,
localField: "_id",
foreignField: "digitalFormId",
as: "forms",
}
},
{
$facet: {
metadata: [{ $count: 'totalRecords' }],
data: [{ $skip: (page - 1) * pageSize }, { $limit: pageSize }],
},
},
])
請注意$facet
階段的使用,它允許我們返回總記錄數以及請求頁面的所有文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.