Sequelize Cheat Sheet
Sequelize documentation is horrendous, so here's a handy cheat sheet.
Sequelize/PostgreSQL commands
Initialize Sequelize
sequelize initUpdate your config/config.js file
config/config.js fileCreate a database
sequelize db:createor
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
authormodel will beauthorId
sequelize model:create --name comment --attributes author:string,content:text,favoriteId:integerCreate a Sequelize Migration (empty by default)
Run all Sequelize migrations
Undo latest Sequelize migration
Sequelize Querying (using a comment model)
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)
post model)createPost()- should create a post when called on a model related to post. Takes attributes as parametersgetPosts()- should get posts when called on a model related to postaddPost(post)- should add an existing post when called on a model related to postsetPost([post1, post2])- should delete all existing associations and add the array of posts when called on a model related to post
Promises
then
thenThis is the default promise called when a query is completed.
spread
spreadThis is used to spread an array of values to parameters. This is only used for findOrCreate, where the callback has two parameters.
catch
catchThis is triggered if something goes wrong (an error).
finally
finallyThis is triggered after all other callbacks (including then, spread, and catch). Can be used for cleanup.
Last updated
Was this helpful?