We need to implement three Express routes that retrieve and order data from a database using Sequelize:
// STEP 1: Order by one attribute
app.get('/bands/latest', async (req, res, next) => {
const bands = await Band.findAll({
order: [['createdAt', 'DESC']] // Orders by creation date, newest first
});
res.json(bands);
});
// STEP 2: Order by multiple attributes
app.get('/musicians/alphabetic', async (req, res, next) => {
const musicians = await Musician.findAll({
order: [
['lastName', 'ASC'], // Primary sort by last name
['firstName', 'ASC'] // Secondary sort by first name
]
});
res.json(musicians);
});
// STEP 3: Order by nested attributes
app.get('/bands/alphabetic-musicians', async (req, res, next) => {
const bands = await Band.findAll({
include: { model: Musician },
order: [
['name', 'ASC'], // Order bands by name
[Musician, 'lastName', 'ASC'], // Order musicians by last name
[Musician, 'firstName', 'ASC'] // Then by first name
]
});
res.json(bands);
});
In Sequelize, the order option accepts an array of arrays. Each inner array specifies:
Think of this like sorting a library:
Alternative ways to write the ordering:
// Using literal SQL
order: [[sequelize.literal('createdAt DESC')]]
// Using an object notation
order: [
{
column: 'lastName',
order: 'ASC'
}
]
// Multiple nested associations
order: [
['name', 'ASC'],
[{ model: Musician }, { model: Instrument }, 'type', 'ASC']
]