Prerequisite
- Kindly ensure you’ve gone through the earlier chapter of this article. mongodb-query-filter-sort-limit-pagination
- You can also get the example data used in this article. tours.json
|
|
Test Case
http://localhost:3000/api/v1/tours?fields=name,durations,price
, Query the data which only return name, durations and pricehttp://localhost:3000/api/v1/tours?limit=10&page=2
, Query the data which skip the first 10 results
Explanation
Field Limiting (start from line 22)
- If the ‘fields’ query paramater is existed, split the parameter from comma to white-space so that it can read and limit multiple fields
- Apply mongoose
select
methods to only return the selected field. - Exclude out the mongo version field ‘__v’ by simply put a negative sign (-) infront
Pagination (start from line 31)
- Pagination is very useful implementation when you are dealing with a very large dataset.
- Combining
.skip
and.limit
methods allow us to achieve pagination..skip
: total records we wanted to skip from the query.limit
: total records we wanted to show from the query
- As we are passing the Page Number
page
and Total Recordslimit
from the query parameters. We can then come out with the formulaconst skip = (page - 1) * limit
. This will let us know how mnay records we are required to skip and paginate to our desire page number