Basic Phase One - SELECT Using Sequelize Queries

Understand the Problem

We want to retrieve data from a database table (Trees) using Sequelize in an Express route. Specifically, we should:

Devise a Plan

  1. Import the Tree model from the models folder.
  2. Create a GET route for /trees to select desired attributes and order by heightFt.
  3. Create a GET route for /trees/:id to find a single tree by primary key.
  4. If no tree is found, return an error response.

Carry Out the Plan (Solution)

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

// Pseudocode for retrieving all trees (simplified):
// GET /trees
// 1. Await Tree.findAll({ attributes: ['heightFt', 'tree', 'id'], order: [['heightFt', 'DESC']] })
// 2. Send JSON response with found trees or error

// Pseudocode for retrieving one tree:
// GET /trees/:id
// 1. Parse the id from req.params
// 2. Await Tree.findByPk(id)
// 3. If null, return error JSON
// 4. Otherwise, return the found tree
    

Expected Input: HTTP GET request with optional :id parameter in the URL.

Expected Output: JSON listing of trees or a single tree object, or an error JSON if none found.

Elementary (Basic) Approach

Possible Advanced Enhancements

Step-by-Step Directions:

  1. Open server/routes/trees.js.
  2. Require the Tree model from ../models.
  3. Add your GET routes, implement findAll or findByPk.
  4. Test in browser or Postman.
  5. Handle errors gracefully with a JSON error message.

Explanations & Analogies: Think of Sequelize findAll like searching for all records in a library’s card catalog. findByPk is like looking up one specific book by its ID number.

Real World Example: A user on a website listing famous trees might click to view each tree’s details.

Further Examples: Filter by partial matches, search by different fields, or join with other data about the insects found on each tree.

Look Back

Once the routes work, confirm your approach is correct using tests and try edge cases (e.g., invalid IDs). Verify correct ordering and data retrieval.