Sequelize는, Node.js v4 이후 사용되기 시작한 ORM입니다. PostgreSQL, MySQL, SQLite, MSSQL 등을 지원하며, 트랙젝션, 릴레이션(관계), 레플리케이션(복제) 등이 가능합니다.
npm으로 시퀄라이즈를 설치합니다.
npm install --save sequelize
자신의 SQL에 맞는 모듈을 설치합니다.
npm install --save pg pg-hstore // Postgres
npm install --save mysql2
npm install --save mariadb
npm install --save sqlite3
npm install --save tedious // Microsoft SQL Server
저는 MySQL을 사용하고 있으므로, MySQL 기준으로 설명합니다.
config 파일을 아래와 같이 설정합니다.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('mysql://username:password@dbhost:3306/dbname', {
//
});
module.exports = sequelize;
혹은 아래와 같이 설정합니다.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mysql',
host: 'localhost',
port: 3306,
})
module.exports = sequelize;
기존에 쓰고 있는 테이블 구조, 혹은 앞으로 사용할 테이블 구조에 맞게 모델을 정의합니다.
const User = sequelize.define('user', {
username: Sequelize.STRING,
id: Sequelize.INTEGER(10).UNSIGNED
});
데이터의 획득, 추가, 갱신, 삭제를 실행합니다.
INSERT는 시퀄라이저에서 다음과 같이 표현할 수 있습니다.
User.create({
username: 'flame91',
id: 1234
});
아래의 로우쿼리(raw query)와 동일합니다.
INSERT INTO USER(username, id) VALUES('flame91', '1234');
여러 개의 데이터를 넣기 위해서는 bulkCreate를 씁니다.
User.bulkCreate([{
username: 'flame91',
id: 1234
},
{
username: 'prog',
id: 5678
}
]);
UPDATE는 시퀄라이저에서 다음과 같이 표현할 수 있습니다.
User.update({
username: 'flame22',
id: 456
});
아래의 로우쿼리와 동일합니다.
UPDATE USER SET username='flame22', id=456;
DELETE는 시퀄라이저에서 다음과 같이 표현할 수 있습니다.
User.delete(123);
SELECT는 시퀄라이저에서 다양하게 표현할 수 있습니다.
// 단일 요소 찾기
User.findOne({
where: {
username: 'flame91',
id: 123
}
});
//찾을 속성(어트리뷰트)을 지정하여 찾기
User.findOne({
where: {
username: 'flame91',
id: 123
}, attributes; ['username']
});
// 여러 요소 찾기
User.findAll({
where: {
id: 123
});
// 요소를 찾고, 없으면 삽입(INSERT)
User.findOrCreate({
where: {
username: 'flame91',
}, defaults:{
id: 123
}
});
// 요소를 찾고, limit(보일 행 개수) 설정
User.findAndCountAll({
where: {
id: 123
},
limit: 10
});
그 외 트랜젝션(transaction), 리터럴(literal), 연산자(Operator) 등은 다음 포스팅에서 다룹니다.
[Sequelize] Cannot read property 'uuid' of undefined (0) | 2020.10.27 |
---|---|
[Sequelize] AssertionError [ERR_ASSERTION]: Missing where attribute in the options parameter (0) | 2020.08.30 |