Intermediate Bonus Phase One - Select WHERE Like

Understand the Problem

We want to implement a search route that finds all trees whose names partially match a given value, e.g., searching “General” should return “General Sherman” and “General Grant.”

Devise a Plan

  1. Import Op from Sequelize.
  2. Implement a GET route: /trees/search/:value.
  3. Use where: { tree: { [Op.like]: '%' + req.params.value + '%' } } to find matches.
  4. Return only certain attributes (id, tree, heightFt) ordered by tree alphabetically or as desired.

Carry Out the Plan (Solution)

File Name & Location: server/routes/trees.js

// GET /trees/search/:value
// 1. import { Op } from 'sequelize';
// 2. const foundTrees = await Tree.findAll({
//      attributes: ['id','tree','heightFt'],
//      where: { tree: { [Op.like]: `%${req.params.value}%` } },
//      order: [['tree','ASC']]
//    });
// 3. return foundTrees as JSON
    

Expected Input: A GET request to /trees/search/someTerm.

Expected Output: An array of tree objects whose tree field contains someTerm.

Elementary (Basic) Approach

Advanced Approach

Step-by-Step Directions:

  1. Open trees.js and add a new route at /search/:value.
  2. Import Op from require('sequelize').
  3. Use where: { tree: { [Op.like]: `%${req.params.value}%` } } inside findAll.
  4. Test with various partial strings in Postman or the browser.

Explanations & Analogies: “Like” queries are akin to searching a phone directory for any name containing certain letters. If value is “ant,” you find “Grant,” “Anthony,” etc.

Real World Example: Adding an autocomplete search feature for a database of products, employees, or in this case, trees.

Look Back

Verify queries with partial matches, no matches, and edge cases (empty search or special characters).