Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

908
Views
How to use mongoose paginate v2 with filter more than one

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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())
   });
};
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!