Querying for data using Mongoose query selectors
Instead of SQL to query data from the database, Mongoose relies on using the JavaScript method chaining to build logical queries, which will be sent over to MongoDB once executed. The model API already exposed us to some rudimentary queries through methods like find
and where
, but we can expand upon those greatly with Mongoose's query API methods.
How to do it...
Let's follow these steps to add query parameters to our Express /api/post
REST endpoint to support pagination. We will also implement some advanced filtering queries, including date range filtering to our API:
- First, we'll extend the list method of our
/middleware/rest.js
middleware to parse query parameters for_size
and_page
from our REST API URL parameters. The underscores are useful to denote that these properties are URL parameters, instead of Mongoose Query API parameters. Whether these properties are provided or not, we will set default values for them using a ternary operator...