Sequelize Basic

Last modified: April 30, 2022

Initializes project

sequelize init
  • It will create folder config with config.json file (containing information about Database connection) and model (if not yet exist)
  • Rename config.json to config.js
    • Import dotenv to read key pair values from environment (.env) file
    • We are going to use MySQL database
config.js
require('dotenv').config(); // this is important! module.exports = { "development": { "username": process.env.MySQL_USER, "password": process.env.MySQL_PASSWORD, "database": process.env.MYSQL_DB, "host": process.env.MySQL_HOST, "dialect": "mysql" }, "test": { "username": "root", "password": null, "database": "database_test", "host": "127.0.0.1", "dialect": "mysql" }, "production": { "username": process.env.MySQL_USER, "password": process.env.MySQL_PASSWORD, "database": process.env.MYSQL_DB, "host": process.env.MySQL_HOST, "dialect": "mysql" } };
  • Create a .env file and put below content to it.
.env
API_PORT=9092 MySQL_HOST=127.0.0.1 MySQL_USER=root MySQL_PASSWORD=London2012! MYSQL_DB=netflix JWT_SECRET_KEY=ASDj23jsdlk2jsdl23ndl32jsk32jsdk23jsdksdjmdj23jsdksdj UserRoleId=1 NODE_ENV=Production
Run migration as development environment
export NODE_ENV=development; npx sequelize db:migrate

If no error, it means we are ready to create models/tables now.

Model

User
npx sequelize-cli model:generate --name User --attributes username:string,password:string,email:string

Above command create two files

  • Model
  • Migration

Model nodejs

Migration nodejs

We create Roles model that hold users' role list e.g. admin

npx sequelize-cli model:generate --name Roles --attributes name:string

We create Person model that hold extra information about a person

npx sequelize-cli model:generate --name Person --attributes firstname:string,lastname:string,country:string

Each user has different user porfiles, e.g. kids

npx sequelize-cli model:generate --name Profile --attributes name:string

Movie table

npx sequelize-cli model:generate --name Movie --attributes title:string,imageurl:string,videourl:string
Run again to sync the database
export NODE_ENV=development; npx sequelize db:migrate