빠른 참조

Sequelize ORM 치트시트

Sequelize 빠른 참조 가이드: Postgres, MySQL, SQLite를 위한 Promise 기반 Node.js ORM, 모델 정의, 쿼리 및 연관 관계.

· 게시일

Sequelize는 Postgres, MySQL, MariaDB, SQLite, SQL Server를 지원하는 Promise 기반의 Node.js ORM입니다.

연결 및 모델 정의

const { Sequelize, DataTypes } = require('sequelize');

const sequelize = new Sequelize('postgres://user:pass@localhost:5432/mydb');

const User = sequelize.define('User', {
  name: {
    type: DataTypes.STRING,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    unique: true,
    validate: { isEmail: true }
  }
});

// 데이터베이스 스키마 동기화
await sequelize.sync();

CRUD 연산

// 생성 (Create)
const user = await User.create({ name: 'Alice', email: '[email protected]' });

// 조회 (Read)
const users = await User.findAll({
  where: { name: 'Alice' },
  order: [['createdAt', 'DESC']],
  limit: 10
});

// 수정 (Update)
await User.update({ name: 'Bob' }, { where: { id: 1 } });

// 삭제 (Delete)
await User.destroy({ where: { id: 1 } });

모델 연관 관계 (Associations)

User.hasMany(Post);
Post.belongsTo(User);

// include를 통한 즉시 로딩 (Eager loading)
const userWithPosts = await User.findOne({
  where: { id: 1 },
  include: [Post]
});

참고자료

관련 주제