Last updated Aug 17, 2022

Filtering, Sorting, and Pagination in Nodejs

Build Node.js APIs with filtering, sorting, and pagination.

Filtering, Sorting, and Pagination in Nodejs

In this article, we will see how to do filtering, sorting, limiting fields, and pagination in nodejs with express.js and mongoose.

Filtering

Case1: Suppose you want to get a blog article, which has an active flag set to true and the category is 'Angular', so in this scenario, we can do this, as below:

Sample Url: https://www.example.com/posts?active=true&category=angular

 const queryObj = { ...req.query };
 const excludedFields = ['page', 'sort', 'limit', 'fields'];
 excludedFields.forEach(el => delete queryObj[el]);
 const posts =  await Post.find(queryObj);

Above first we have made clone of object and exscluded some query params from query obj to later uses.

Now let's make it advance and add another feature like filtering with less then, greater then value, for instacne in our example we need posts whose views are greater then 1000, let's see how we can do it:

Sample URL : https://www.example.com/posts?views[gte]=1000

 const queryObj = { ...req.query };
 const excludedFields = ['page', 'sort', 'limit', 'fields'];
 excludedFields.forEach(el => delete queryObj[el]);

 // Advanced filtering
 let queryStr = JSON.stringify(queryObj);

//Replaced string gte to $gte
 queryStr = queryStr.replace(/\b(gte|gt|lte|lt)\b/g, match => `$${match}`);

 const result = await Post.find(JSON.parse(queryStr));

Sorting

Now suppose we want to sort our blog post article by specifc criteora or default to created date, let's do it :

sample URL: https://www.example.com/posts?sort=views

 if (req.query.sort) {
      // if there is multiple sort option, replace (,)comma with space
      const sortBy = req.query.sort.split(',').join(' ');
      this.query = this.query.sort(sortBy);
    } else {
      this.query = this.query.sort('-createdAt');
    }

In above example first, we will check is there any specifc recommnadaton for sorting? if not then default sort by created date at decending order.

Limiting Fields

There is alway good prtatice to send only specifc and required fileds to client side, instead of sending whole objetc from database,we can do that using:

Sample URL: https://www.example.com/posts?fields=name,author,slug

 if (req.query.sort) {
      const fields = req.query.sort.fields.split(',').join(' ');
      this.query = this.query.select(fields);
    } else {
      //remove default __v fields from result
      this.query = this.query.select('-__v');
    }

Pagination

Sample Url: https://www.example.com/posts?page=2&limit=10

 const page = this.queryString.page * 1 || 1;
 const limit = this.queryString.limit * 1 || 100;
 const skip = (page - 1) * limit;

 this.query = this.query.skip(skip).limit(limit);

Tags

Available for projectsLet’s build together

Need this built properly,
not just explained?

I take on Angular and NestJS work directly — auth systems, multi-tenant SaaS, API rewrites and the deploy pipeline underneath them. You talk to the person writing the code.

Projects delivered
20+ Projects delivered
Angular • NestJS
7+ years Angular • NestJS
Average reply time
1 day Average reply time

What I can help with

  • Auth and permissions systems
  • Multi-tenant SaaS foundations
  • API design and rewrites
  • Deploy pipelines and VPS setup
  • Bug fixing and performance optimization
Send me a message

Tell me about your project and I’ll get back with a realistic scope and price.

Turn
Your Ideas
Into Reality

Stay in the loop

Get the finished tutorials, projects and resources in your inbox.

Join 5,000+ developers and get new tutorials, source code, product updates and exclusive content — straight to your inbox.

  • No spam
  • Useful content only
  • Unsubscribe anytime

Subscribe to TutsCoder

Be the first to get new tutorials, projects and tips.

Join 5,000+ developers already learning with us.

Learn
Build
Grow

Discussion

Comments

Share your thoughts, ask questions or suggest improvements. Let’s learn and grow together!

Loading comments…

Join the discussion

Sign in to join the discussion. Your account also keeps your saved tutorials and path progress.