Answer a question

I have a pipeline with $facet and using pagination inside it with $skip and $limit. I want to implement a condition when parameters are passed to skip and limit then only pagination should work else it should return me all the records.

Model.aggregate([
    {
      $facet: {
        comments: [
          {
            $match: { issueId: Types.ObjectId(issueId) },
          },
          {
            $skip: skip,
          },
          {
            $limit: parseInt(size, 10),
          },
          {
            $lookup: {
              from: 'users',
              localField: 'createdBy',
              foreignField: '_id',
              as: 'commentedBy',
            },
          },
        ]
      }
    }
]

Answers

Try separating all pipeline on the base of condition,

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 } }]);

Second option using concat array function 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',
        }
      }]
    )
  }
]);
Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐