Sequelize Cheat Sheet

Sequelize documentation is horrendous, so here's a handy cheat sheet.

Sequelize/PostgreSQL commands

Initialize Sequelize

sequelize init

Update your config/config.js file

Create a database

sequelize db:create

or

createdb <database name>

Create a Sequelize Model

NOTE: The model name will be singular

NOTE 2: Any foreign keys will be modelNameId

  • example: a foreign key to an author model will be authorId

sequelize model:create --name comment --attributes author:string,content:text,favoriteId:integer

Create a Sequelize Migration (empty by default)

Run all Sequelize migrations

Undo latest Sequelize migration

Sequelize Querying (using a comment model)

Create

Find or Create

Find

Find + Eager Load

Find All

Find By Id

Find One

Update

Destroy

Associations

1:M

Adding associations (using author and post models)

author.js

Authors should have many posts

post.js

A post should belong to an author

M:M

Adding associations (using post and tag models, with a join table called postsTags)

post.js

A post should belong to many tags

tag.js

A tag should belong to many posts

Helper Functions (using a post model)

  • createPost() - should create a post when called on a model related to post. Takes attributes as parameters

  • getPosts() - should get posts when called on a model related to post

  • addPost(post) - should add an existing post when called on a model related to post

  • setPost([post1, post2]) - should delete all existing associations and add the array of posts when called on a model related to post

Promises

then

This is the default promise called when a query is completed.

spread

This is used to spread an array of values to parameters. This is only used for findOrCreate, where the callback has two parameters.

catch

This is triggered if something goes wrong (an error).

finally

This is triggered after all other callbacks (including then, spread, and catch). Can be used for cleanup.

Last updated

Was this helpful?