Intermediate Phase Four - UPDATE Using Sequelize Queries

Understand the Problem

We need to update the existing tree record with new values, ensuring the id from the URL matches the id in the request body. If a mismatch or a non-existent id occurs, handle it gracefully.

Devise a Plan

  1. Check if req.params.id matches req.body.id; if not, return an error.
  2. Use Tree.findByPk to get the existing record.
  3. If found, update fields: tree (name), location, heightFt (height), groundCircumferenceFt (size), etc.
  4. Save and return the updated record as JSON.
  5. If no record found, respond with “not-found” error.

Carry Out the Plan (Solution)

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

// PUT /trees/:id pseudocode:
// 1. if (req.params.id !== req.body.id) return error
// 2. let tree = await Tree.findByPk(req.params.id)
// 3. if (!tree) return error (not found)
// 4. tree.tree = req.body.name
// 5. tree.location = req.body.location
// 6. etc...
// 7. await tree.save()
// 8. respond with updated tree
    

Expected Input: A PUT request with both URL param :id and id in the JSON body, plus updated fields (name, location, etc.).

Expected Output: JSON object with the updated tree or an error JSON if mismatch or not found.

Elementary (Basic) Approach

Advanced Approach

Step-by-Step Directions:

  1. Ensure the route is declared: PUT /trees/:id.
  2. Compare req.params.id and req.body.id.
  3. Find the tree by primary key.
  4. Update the fields needed, then await tree.save().
  5. Send the updated tree as a JSON response or send error if not found.

Explanations & Analogies: Updating is like editing the details of a saved library entry. If you reference the wrong ID, you can’t edit that entry.

Real World Example: Editing an item in an online store to fix its name or price.

Look Back

Confirm the correct record was updated by fetching it again. Test with invalid IDs or mismatched IDs to ensure the correct error response.