SELECT Using Sequelize Queries

Understanding the Problem

We need to implement Sequelize queries to SELECT data from a database in Express routes. This involves:

Planning the Solution

  1. Import Tree model from the models directory
  2. Implement GET / route to list all trees
  3. Add attribute selection and ordering
  4. Implement GET /:id route
  5. Add error handling for invalid IDs

Solution

File Location: server/routes/trees.js

Step 1: Import Model


// Import Tree model from models directory
const { Tree } = require('../db/models');
    

Step 2: List All Trees Route


// GET route to list all trees
router.get('/', async (req, res) => {
    // Use Sequelize's findAll method to get trees
    const trees = await Tree.findAll({
        attributes: ['heightFt', 'tree', 'id'],  // Select only these attributes
        order: [['heightFt', 'DESC']]  // Order by height descending
    });
    res.json(trees);
});
    

Step 3: Find One Tree Route


// GET route to find one tree by ID
router.get('/:id', async (req, res, next) => {
    // Get tree by primary key (id)
    const tree = await Tree.findByPk(req.params.id);
    
    // Handle case where tree is not found
    if (!tree) {
        const err = new Error("Could not find tree");
        err.status = "not-found";
        err.statusCode = 404;
        err.details = "Tree not found";
        return next(err);
    }
    
    res.json(tree);
});
    

Testing the Solution

Test the implementation using:

npm test test/phase-01-spec.js

Real World Application

This pattern is commonly used in applications that need to:

Common Pitfalls

Advanced Solutions

More advanced implementations might include: