본문 바로가기

항해99_10기/105일의 TIL & WIL

[4주차][20221203] node.js에서 mySQL을 사용하기 위해 알아야 하는 것들 : Sequelize, Migration, Model

오늘은 mySQL을 node.js 환경에서 사용하는 방법을 배웠다.

 

솔직히 세션 중간에 졸았는데.. 이해가 하나도 안됐다..ㅠㅠ

 

일단, mongodb는 순한맛이었다.

mySQL을 사용하기 위해서는 모델(스키마)만 있어서는 안되고, 마이그레이션이라는 것을 통해서 db를 설정해 준다음에 모델을 업데이트 하여 사용해야 했다. (일단 여기서부터 이해가 안가서..ㅋㅋ)

 

마이그레이션, 모델, 시퀄라이즈... 이름부터 무시무시해서.. 네 놈들의 정체는 무엇이냐!! 하고 검색을 해봤다.

 

1. Sequelize

Sequelize is a modern TypeScript and Node.js ORM for Oracle, Postgres, MySQL, MariaDB, SQLite and SQL Server, and more. Featuring solid transaction support, relations, eager and lazy loading, read replication and more.
- Sequelize

Sequelize 홈페이지에 들어가서 보니, 요놈은 TypeScript와 Node.js의 ORM이라고 한다.

잠깐, ORM이 뭐지???

 

Object–relational mapping (ORM, O/RM, and O/R mapping tool) in computer science is a programming technique for converting data between type systems using object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language.
- Wikipedia

위키피디아에서는 ORM을 타입 시스템과 객체지향 프로그램 언어 사이에서 데이터를 변환해주는 프로그래밍 기술이라고 소개하고 있다. 프로그래밍 언어 내에서 사용할 수 있는 "가상의 객체 데이터베이스"를 구성해주는 기술이라고 한다.

조금 더 쉽게 설명하자면, 내가 사용하는 JS는 객체지향언어이고, MySQL은 타입 시스템인데, 객체지향으로 작성한 데이터를 타입 시스템에 저장하고, 또 타입 시스템으로 저장된 데이터를 다시 객체로 변환하여 사용할 수 있게해주는 변환 프로그램인 것이다.

 

2. migration

이제 sequelize에 대해 알아보았으니, 다음으로 마이그레이션이 뭔지 알아보자.

Just like you use version control systems such as Git to manage changes in your source code, you can use migrations to keep track of changes to the database. With migrations you can transfer your existing database into another state and vice versa: Those state transitions are saved in migration files, which describe how to get to the new state and how to revert the changes in order to get back to the old state.
- Sequelize

Sequelize  홈페이지에 나온 설명을 보면, Migration은 Git과 같은 버전 컨트롤 시스템인데, 데이터 베이스와 관련한 변화를 트래킹 해주는 일종의 버전 컨트롤 시스템이라고 한다. 현재 존재하는 데이터 베이스의 상태를 다른 상태로 전환할 수 있는데, 각각의 상태 전환이 migration  파일에 기록되어 저장된다고 한다. 데이터 베이스 상태를 변환했다가, 다시 되돌리고 싶을 때 git과 같이 사용할 수 있는 것 같다.

 

Sequelize에서 제공하는 Migration은 up과 down 함수를 export하는 JS 파일인데, 해당 함수를 통해 마이그레이션을 수행하거나 undo 할 수 있다. 해당 함수는 Sequelize.query 등 Sequelize에서 제공하는 메소드를 사용해 개발자가 직접 작성 해야 하지만, 함수를 콜 하는 것은 직접 할 수 없고, CLI(Commend Line Interface)에 의해 자동으로 콜 된다고 한다.

module.exports = {
  up: (queryInterface, Sequelize) => {
    // logic for transforming into the new state
  },
  down: (queryInterface, Sequelize) => {
    // logic for reverting the changes
  }
}

// 예제
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Person', {
      name: Sequelize.DataTypes.STRING,
      isBetaMember: {
        type: Sequelize.DataTypes.BOOLEAN,
        defaultValue: false,
        allowNull: false
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Person');
  }
};

 

3. Model

Model은 Sequelize의 가장 중요한 부분이라고 한다. 바로 db 테이블을 추상화한 것이다. db 테이블에서 각각의 엔티티의 이름과 어느 컬럼에 위치해야 하는지를 나타내는 가장 중요한 부분이라고 할 수 있다.

이런 모델은, sequelize.define()함수를 콜해서 아래와 같이 지정할 수 있다.

 

const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');

const User = sequelize.define('User', {
  // Model attributes are defined here
  firstName: {
    type: DataTypes.STRING,
    allowNull: false
  },
  lastName: {
    type: DataTypes.STRING
    // allowNull defaults to true
  }
}, {
  // Other model options go here
});

// `sequelize.define` also returns the model
console.log(User === sequelize.models.User); // true

 

뭐.. 대략 지금까지 사용해 오던 몽고디비와는 상당히 다른 체계를 가지고 있어서 매우 기초적인 부분부터 새로 공부가 필요했다. 오늘은 대략 각각의 용어가 의미하는 것과, 어떻게 사용하는지에 대해서 배워봤는데, 자세한 사용 방법에 대해서는 내일 다시 코드를 뜯어보고, 직접 작성해보면서 배워야겠다...!