Home / Blogs / Node.js

Put Sequelize associations in one place

Fifty models is not the problem. Loading all of them on every request is.

Sequelize projects get hard to change when relationships are a side effect of importing a file. The rules that avoid that are dull, which is the point.

Do not associate on import

Calling associate() from inside a model file depends on import order. The failure looks like a missing function and points at the wrong file. Register every model, then run one associations module.

Order.belongsTo(User, { as: "assignee", foreignKey: "assigneeId" });
Order.hasMany(Note, { foreignKey: "orderId" });

A new table gets a line there and a migration. It does not get a hidden call at the bottom of the model.

Migrations, not sync

Do not run sequelize.sync() against a database that already holds rows. Sync will invent a column. It will not invent the backfill, and it will not leave a history the next person can read. A model change without a migration is a fiction that exists on one laptop.

If a database trigger stamps a time, keep that trigger in SQL next to the migration. Do not also reimplement it as a hook. Two writers for one timestamp drift.

A list route names its columns

There is no default include of the whole graph "for convenience." That convenience is how a list starts joining notes and files for every row. The list wants an id, a status, an assignee, and a time. The detail route can afford the graph.

This is why a screen should fetch what it renders instead of reading a context object that already loaded everything.

Topics Node.jsDatabase