How to use mongoose paginate v2 with filter more than one

Viewed 3633

I use Monggose-paginate-v2 for make a paginate with nodejs, but i have a problem with how to use this library with more than 1 filter or query?

My Code

exports.allData = (req, res, next) => {
  const { page, size, title, active } = req.query;
  var condition = title ? { title: { $regex: new RegExp(title), $options: "i" } } : {};
  var condition2 = active ? { active: { $regex: new RegExp(active), $options: "i" } } : {};
  const { limit, offset } = getPagination(page, size);

  var options = {
    populate: [{
      path: 'category',
      select: 'name'
    }],
    sort: ({ createdAt: -1 })
  };

  Article.paginate(condition, condition2, { offset, limit, options })
    .then((data) => {
      res.send({
        totalItems: data.totalDocs,
        articles: data.docs,
        totalPages: data.totalPages,
        currentPage: data.page - 1,
      });
    })
    .catch((err) => {
      logger.error(req.method + ": " + req.originalUrl + ", message: " + err.message)
      next(createError.InternalServerError())
    });
};

I use condition, condition2 in one line, its didnt work. Thanks before.

1 Answers
pass conditional query as shown below

exports.allData = (req, res, next) => {
    const { page, size, title, active } = req.query;
    // query documents based on  condition
    let query={};
    if(title){
        query.title={ $regex: new RegExp(title), $options: "i" }
    }
    if(active){
        query.active={ $regex: new RegExp(active), $options: "i" }
    }

    const { limit, offset } = getPagination(page, size);

    var options = {
      populate: [{
        path: 'category',
        select: 'name'
      }],
      sort: ({ createdAt: -1 })
    };

   Article.paginate(query, { offset, limit, options })
   .then((data) => {
      res.send({
        totalItems: data.totalDocs,
        articles: data.docs,
        totalPages: data.totalPages,
        currentPage: data.page - 1,
      });
   })
   .catch((err) => {
       logger.error(req.method + ": " + req.originalUrl + ", message: " + err.message)
       next(createError.InternalServerError())
   });
};
Related