Sequelize CLI Quick Reference
Reference
February 22, 2019
I found this video to be very helpful for getting a start with using Sequelize CLI. I think I watched it at least 20 times to view and review the information. So for posterity’s sake and to avoid shuttling through this video again in the future, here is my summary:
Sequelize Migrations are useful because they let you change the structure of your database tables after they have already been created, even if they contain data. The changes are incremental and reversible (though it’s important to note, dropping existing data during a migration is not reversible).
A migration must contain an up
function (the change you want to make) and a down
function (the code to undo the same change). The migrations make use of Sequelize’s QueryInterface API to do things like bulkInsert
, addColumn
, or changeColumn
, etc.
Sequelize CLI Commands
Commands: |
Setting Up a Project Using Sequelize CLI With Migrations
I wrote up a detailed step-by-step in this post. The short version is as follows…
Creating a Model
A model and create
migration file can be created with one command:
sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string,registered:boolean,age:integer |
This command creates the basic structure of each file. Add any modifications (such as validations, constraints, etc.) to both the model file and the migration file if necessary.
Add associations to the model file.
Run the db:migrate
command to persist the model(s) to the database, and db:migrate:undo
to reverse the changes.
Modify A Table With A Migration
Create a new migration with a similar command to:
sequelize migration:create --name add-title-to-todos |
The file will be an empty structure and you will need to fill in the migration instructions. Here is an example of a migration that will add a new column to the data table:
; |
Don’t forget to also update the model file manually. Sequelize CLI does not automatically update the model when a structure-changing migration is run against the model.