We want to fetch Trees alongside their related Insects (and vice versa) using Sequelize. For one route, we’ll use eager loading with include, and for the other, we’ll demonstrate lazy loading.
/trees-insects that uses eager loading: Tree.findAll({ include: Insect }) with only specific attributes in Insect and sorting./insects-trees that fetches insects first, then uses lazy loading with something like insect.getTrees().File Name & Location: server/routes/joined.js
// Eager loading approach example (trees-insects):
// GET /trees-insects
// 1. const treesWithInsects = await Tree.findAll({
// include: [{
// model: Insect,
// attributes: ['id','name'],
// through: { attributes: [] }, // omit join table columns
// order: [['name','ASC']]
// }]
// });
// 2. Optionally filter out any tree that has no insects
// Lazy loading approach example (insects-trees):
// GET /insects-trees
// 1. const insects = await Insect.findAll({ ... });
// 2. for each insect, call insect.getTrees({ attributes: ['id','tree'] })
// 3. combine results into a final JSON object to send
Expected Input: GET requests to /trees-insects or /insects-trees.
Expected Output: Arrays of objects with nested arrays of related items, each limited to certain attributes.
include or getTrees() with minimal filtering and ordering.through: {'attributes': []}.Step-by-Step Directions:
joined.js, create /trees-insects using findAll with include./insects-trees with a loop or map, calling insect.getTrees() for each record.Explanations & Analogies: Eager loading is like checking out a library book and automatically bringing along the shelf info. Lazy loading is when you first get the book details, then go back and request the shelf data only if you need it.
Real World Example: If your user interface always needs the related data, eager load it. If you only show details on demand, lazy load can reduce initial overhead.
Run your tests or check the JSON responses. Confirm that the data includes only the desired fields and that missing associations are handled properly.