Basic Phase Three - DELETE Using Sequelize Queries

Understand the Problem

We want to remove a tree record from the database when given an id. If the id does not exist, we should handle that gracefully.

Devise a Plan

  1. Read the id from req.params.
  2. Use Tree.destroy with a where condition matching the id.
  3. If no rows are destroyed, respond with an error JSON (“Tree not found”).
  4. Otherwise, respond with success JSON.

Carry Out the Plan (Solution)

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

// DELETE /trees/:id pseudocode:
// 1. Read id from req.params.id
// 2. const deleted = await Tree.destroy({ where: { id } })
// 3. if (deleted === 0) { return error response }
// 4. otherwise, return success JSON
    

Expected Input: A DELETE request to /trees/:id.

Expected Output: A JSON success message or a “not found” error JSON.

Elementary (Basic) Approach

Advanced Possibilities

Step-by-Step Directions:

  1. Open trees.js and find or create the DELETE route.
  2. Fetch the id from req.params.
  3. Call Tree.destroy passing in a where object.
  4. Check if the destroy count is zero; if so, return an error response.
  5. Test with Postman and confirm the tree is removed from the GET results.

Explanations & Analogies: Deleting a record is like permanently removing a book card from the library system. If the book card doesn’t exist, you can’t remove it.

Real World Example: Removing a no-longer-valid record from an inventory or user database.

Look Back

Confirm the record is indeed removed. Try deleting the same id again to ensure your “Tree not found” logic is triggered.