We need to implement Sequelize queries to SELECT data from a database in Express routes. This involves:
// Import Tree model from models directory
const { Tree } = require('../db/models');
// 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);
});
// 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);
});
Test the implementation using:
npm test test/phase-01-spec.js
This pattern is commonly used in applications that need to:
More advanced implementations might include: