Sequelize Cheat Sheet

In progress

Sequelize is a promise-based ORM for Node.js: models are JavaScript classes mapped to SQL tables (PostgreSQL, MySQL, MariaDB, SQLite, SQL Server), and every query returns a promise.

Overview

Benefit What it means in practice
JavaScript only models and queries without hand-written SQL
Parameterised queries values are escaped for you, which blocks SQL injection through normal query methods
Migrations and seeders schema changes versioned with the CLI

Details

CLI Setup

npm install sequelize sequelize-cli
npx sequelize-cli init                  # config/, models/, migrations/, seeders/
npx sequelize-cli model:generate --name User \
  --attributes firstName:string,lastName:string,email:string
npx sequelize-cli db:migrate

Install the CLI per project (npx) rather than globally, so every machine runs the same version.

Queries with async/await

app.get("/users/:id", async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id);   // findById was removed in v5
    if (!user) return res.status(404).end();
    res.json(user);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: "Internal error" });
  }
});

References

Review cards

Flashcard Why is it important to use `replacements` or `bind` when using `sequelize.query()`?

Because sequelize.query() with values concatenated into the SQL string is as injectable as raw SQL, and using replacements or bind helps prevent SQL injection.