Sequelize ORM의 기본적인 사용 방법을 정리(공식문서에서도 가장 기본적인 것만 발췌)
1. sequelize 설치
npm install --save sequelize
2. sequelize-cli 설치 (마이그레이션을 할 수 있도록 돕는 툴, CLI에서 모델을 생성해 주거나, 스키마 적용을 할 수 있도록 돕는다.)
npm install --save-dev sequelize-cli
3. cli를 통해 ORM을 사용할 수 있도록 해주는 Bootstraping(프로젝트 초기 단계를 자동으로 설정할 수 있도록 도와주는 일)
npx sequelize-cli init
성공적으로 bootstraping이 끝나면 다음 파일 및 폴더들이 생성
config/config.json
models/
migrations/
seeders/
config/config.json에서 mysql의 username과 password등을 설정, database를 특정(필요하다면 db:create 커맨드를 통해 만들 수도 있다.)
4. 모델 생성
model:generate
이 명령어에는 두가지 옵션이 존재. (name: 모델의 이름 / attributes: 모델속성(컬럼)의 목록)
ex) npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
*Note: Sequelize will only use Model files, it's the table representation. On the other hand, the migration file is a change in that model or more specifically that table, used by CLI. Treat migrations like a commit or a log for some change in database. (잘 읽어볼것!)
5. 마이그레이션 실행
npx sequelize-cli db:migrate
스키마 변경이 있을때마다 마이그레이션을 실행해줘야 한다.
This command will execute these steps:
- Will ensure a table called SequelizeMeta in database. This table is used to record which migrations have run on the current database
- Start looking for any migration files which haven't run yet. This is possible by checking SequelizeMeta table. In this case it will run XXXXXXXXXXXXXX-create-user.js migration, which we created in last step.
- Creates a table called Users with all columns as specified in its migration file.
* 마이그레이션 실행 되돌리기 (가장 최근에 실행한 마이그레이션 실행을 되돌리기)
npx sequelize-cli db:migrate:undo
모든 마이그레이션을 다 되돌릴 경우에는 뒷부분을 db:migrate:undo:all 로 해준다.
6. SQL을 대신할 각종 Sequelize Query들
...
Sequelize 공식문서: https://sequelize.org/