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)
})
}
我想在这个功能上添加限制和页面,请帮助我
要添加分页,可以在aggregate
方法中使用$skip
和$limit
。
$skip
跳过特定数量的文档;$limit
限制传递到管道下一阶段的文档数量。
他是你函数的更新版本:
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
阶段的使用,它允许我们返回总记录计数,以及请求页面的所有文档。