Mongoose: Sorting, Pagination, and Filterting

Taken by Nikolas

The Problem

The Solution

Filter

router.get('/tasks', auth, async (req,res) => {const match = {}if(req.query.completed){    match.completed = req.query.completed === 'true' }try{   await req.user.populate({    path:'tasks',     match,    options:{       limit: parseInt(req.query.limit),       skip: parseInt(req.query.skip),       sort  }}).execPopulate()   res.send(req.user.tasks)}catch(e){   res.send(e).status(500)}})
Ex: Get/tasks?completed=truereq.user.tasks = [
{'description': 'Create a medium blog', 'completed': true},
{'description': 'This is an example task', 'completed': true}]

Sort

const sort = {}if(req.query.sortBy){   const parts =  req.query.sortBy.split(':')   sort[parts[0]] = parts[1] === 'desc'? -1: 1;}try{   await req.user.populate({      path:'tasks',       options:{         limit: parseInt(req.query.limit),         skip: parseInt(req.query.skip),         sort      }   }).execPopulate()   res.send(req.user.tasks)}catch(e){   res.send(e).status(500)}})Ex. GET/tasks?sortBy=createdAt:descoutput // [
{description:'Created Last', completed: true},
{description:'Created Second', completed: false},
{description: 'Created First', completed: true}]

Pagination

try{await req.user.populate({   path:'tasks',    options:{      limit: parseInt(req.query.limit),       skip: parseInt(req.query.skip),      sort   }}).execPopulate()   res.send(req.user.tasks)}catch(e){   res.send(e).status(500)}
Ex 1. Get/tasks?limit=2&skip=2
//This is essentially saying, give me tasks 3 and 4!
output// [
{description:'This is task 3',completed: true},
{description: 'this is task 4', completed: false}]
Ex2. Get/tasks?limit=3&skip=6
output// [{description:'This is task', completed:true},
{description: 'This is task 8', completed: true},
{description: 'This is task 9', completed: false}]

Software Engineer based out of NYC. Learning more about programming everyday 👍

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store