Bootcamp
Search…
4.1.1: Intro to Sequelize

Introduction

Sequelize allows us to specify all aspects of our DB schema with JavaScript and provides methods to generate and run SQL queries. This module summarises the setup and core features of Sequelize.
Sequelize is an abstraction on top of SQL and Postgres. When we call a Sequelize method to query the DB, it performs the following steps.
  1. 1.
    Sequelize generates a SQL query using the invoked Sequelize method and relevant parameters
  2. 2.
    Sequelize runs that SQL query through the Pg library, as we have been doing in previous modules
  3. 3.
    Pg executes that SQL query on the connected Postgres DB

Setup Packages and Folders

Setup Packages

Configure Database

Configure Database

Create Tables (Migrations)

Create Tables (Migrations)

Further explanation of migrations

Further Explanations of Migrations

Models

Models

Use Sequelize in App Logic

Use Sequelize in App Logic

Exercise

Replicate the above code and functionality on your computer. If you run into trouble, you can follow along in the PTBC1 Class Recording below.

Further Reading

Read more on other ways to query Sequelize models in Sequelize docs.
Why do Sequelize models and migrations look the same?
When we begin a project, we'll start with a migration of all the tables we have models for. During bootcamp, when changes are made to the database structure these two files can simply be edited to mirror each other.
An alternate workflow is to use a new migration file for each new change to the database. A migration will help preserve the data in a deployed Heroku database, but this would likely be unnecessary, since even during a Bootcamp project, there is likely no "real" user generated data inside the deployed Heroku database.
Sequelize has a setting to automate this duplication between model and migration called sync- this setting eliminates the need for migrations at all by syncing the models to the database.
However, in production when we need to control the *running production database* separately from our models, migrations become important because the database is not in the repo, and in a production environment there is a need to be very, very careful with live user data. Migrations allow a workflow where incremental changes can be made against the live database, ensuring the most careful workflow possible. The default Sequelize sync functionalities do not allow for this. Further reading on sync in production here and here.