Basic Phase Two - INSERT Using Sequelize Queries

Understand the Problem

We need to add a new tree record to our database via Sequelize’s create method. We also must handle:

Devise a Plan

  1. Parse input from req.body to get name, location, height, and size.
  2. Use Sequelize create on the Tree model with correct field mapping.
  3. Return a JSON object containing the newly created tree data.
  4. Catch errors and handle duplicates or missing fields.

Carry Out the Plan (Solution)

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

// Basic pseudocode for POST /trees:
// 1. Extract name, location, height, size from req.body
// 2. Use Tree.create({ tree: name, location, heightFt: height, groundCircumferenceFt: size })
// 3. Respond with JSON containing newly created record
// 4. If error (e.g., duplicate), respond with error JSON
    

Expected Input: A POST request body with valid fields (name, location, height, size).

Expected Output: JSON with the new tree’s details or an error message if invalid.

Elementary (Basic) Approach

Advanced Approach

Step-by-Step Directions:

  1. Open trees.js and locate the POST route.
  2. Extract form data with req.body.
  3. Map fields: tree to name, heightFt to height, etc.
  4. Call Tree.create(...) with the mapped data.
  5. Send the created result as JSON.
  6. Test with Postman for duplicates, missing fields, etc.

Explanations & Analogies: create is like filling out a new library card for a book and inserting it into the system. If the book’s title already exists, the system complains.

Real World Example: A user inputs details about a newly discovered tree in a nature preserve.

Further Examples: Validation (all text fields exist, numeric fields in correct range) to reduce data errors.

Look Back

Check if newly inserted tree records appear in subsequent GET requests. Confirm that a second insertion of the same name is handled gracefully.