-
Notifications
You must be signed in to change notification settings - Fork 0
Lesson 07 Using Query Parameters
Lesson 7 parses the query parameters on a REST get request, and filters the result based on those parameters. The idea is that one can search by any or all of these attributes: featured, name, price, rating, company. For the numeric fields price and rating, one can also specify greater than, less than, or equal to. One can also specify a sort order. Also one can specify a skip and a limit, to facilitate pagination through the result. The starter code is in the 04-store-api/starter directory, with an answer provided in the 04-store-api/final directory. A json file and a populate module are provided so that students can populate their databases with sample data. No front end is provided, so it is very important that students test their work with Postman.
Lesson 7 is quite tricky, and I don’t expect the students will understand all of it, but by repeatedly listening to sections of the video, and perhaps by having a peek at the instructor’s solution, they should be able to complete the assignment. There is, for example, some use of regular expressions, which is a subject the students are probably unfamiliar with. The assignment creates an Express server, and it’s a good opportunity to review the elements of an Express server: routes, controllers, models.
You may also want to mention regular expressions, but it is wise not to focus on these too much, because that would take time from explaining Express.
One of the things that is especially confusing is this business:
let result = Product.find(queryObject);
// sort
if (sort) {
const sortList = sort.split(',').join(' ');
result = result.sort(sortList);
} else {
result = result.sort('createdAt');
}
if (fields) {
const fieldsList = fields.split(',').join(' ');
result = result.select(fieldsList);
}
const page = Number(req.query.page) || 1;
const limit = Number(req.query.limit) || 10;
const skip = (page - 1) * limit;
result = result.skip(skip).limit(limit);
// 23
// 4 7 7 7 2
const products = await result;
Now here, the initial Product.find() call returns a Query object, which is a thenable. The instructor does not explain thenables, but they are explained on the lesson page. We have been treating the Query object like a promise, and in fact, it can be used as a promise with an await call. But until the await call is made, the query is not dispatched to the database, so it can be further modified with various Query helper methods provided by Mongoose. These helper methods are described in the Mongoose documentation. This should be explained to the students.