我有一个带有 $facet
的管道,并在其中使用 $skip
和 $limit
进行分页。我想在参数传递给skip和limit时实现一个条件,那么只有分页应该起作用,否则它应该返回所有记录。
Model.aggregate([
{
$facet: {
comments: [
{
$match: { issueId: Types.ObjectId(issueId) },
},
{
$skip: skip,
},
{
$limit: parseInt(size, 10),
},
{
$lookup: {
from: 'users',
localField: 'createdBy',
foreignField: '_id',
as: 'commentedBy',
},
},
]
}
}
]
最佳答案
尝试根据条件分离所有管道,
let pagination = true; // true for add, false for remove
// initialise default comments array
let comments = [];
// set match stage
comments.push({ $match: { issueId: Types.ObjectId(issueId) } });
// if pagination is required, put you condition to enable disable pagination
if (pagination === true) {
comments.push({ $skip: skip });
comments.push({ $limit: parseInt(size, 10) });
}
// lookup
comments.push({
$lookup: {
from: 'users',
localField: 'createdBy',
foreignField: '_id',
as: 'commentedBy',
},
});
// execute query
Model.aggregate([{ $facet: { comments: comments } }]);
使用 concat 数组函数的第二个选项 Array.prototype.concat ,
let pagination = true; // true for add, false for remove
Model.aggregate([
{
$facet: Array.prototype.concat(
[{ $match: { issueId: Types.ObjectId(issueId) } }],
(
pagination == true ? [{ $skip: skip }, { $limit: parseInt(size, 10) }] : []
),
[{
$lookup: {
from: 'users',
localField: 'createdBy',
foreignField: '_id',
as: 'commentedBy',
}
}]
)
}
]);
关于node.js - $limit 和 $skip 在 MongoDB 聚合管道中作为可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67373807/