만능재주꾼

[Node.js 교과서] 7장 MySQL 정리하기 본문

💻 Node.js

[Node.js 교과서] 7장 MySQL 정리하기

유고랭 2021. 3. 17. 02:10

✔️ 시퀄라이즈(Sequelize): MySQL 작업을 도와주는 라이브러리로, ORM으로 분류된다.

     👉🏻여기서 ORM이란! Object-relational Mapping으로 자바스크립트 객체와 데이터베이스의 관계를 매핑해주는 도구이다.


⭐️ 시퀄라이즈를 이용해 MySQL 연결하기

  🗂 models

 

    ✔️index.js -> Sequelize 객체를 이용해 MySQL 연결 객체 생성

'use strict'

const Sequelize = require('sequelize');
const User = require('./user');
const Comment = require('./comment');

const env = process.env.NODE_ENV || 'development';
const config = require('../config/config')[env]; //이 경로를 통해 데베 설정을 불러옴
const db = {};

//Sequelize 객체를 통해 MySQL연결 객체 생성
const sequelize = new Sequelize(config.database,config.username,config.password,config);

/* db 객체에 담기 */
db.sequelize = sequelize; 
db.User = User;
db.Comment = Comment;

/* 각 모델의 static.init 메서드 호출 */
User.init(sequelize);
Comment.init(sequelize);

/* 다른 테이블과의 관계 연결 */
User.associate(db);
Comment.associate(db);

module.exports = db;

    ✔️user.js -> MySQL에서 정의한 user 테이블을 시퀄라이즈에서도 정의하기

'use strict'

const Sequelize = require('sequelize');

module.exports = class User extends Sequelize.Model{
    /* 테이블에 대한 설정 */
    static init(sequelize) {
        return super.init({
            name: {
                type: Sequelize.STRING(20),
                allowNull: false,
                unique: true,
            },
            age: {
                type: Sequelize.INTEGER.UNSIGNED,
                allowNull: false,
            },
            married: {
                type: Sequelize.BOOLEAN,
                allowNull: true,
            },
            created_at: {
                type: Sequelize.DATE,
                allowNull:false,
                defaultValue: Sequelize.NOW,
            },
        }, {
            sequelize,
            timestamps: false,
            underscored: false,
            modelName: 'User',
            tableName: 'users',
            paranoid: false,
            charset: 'utf8',
            collate: 'utf8_general_ci',
        });
    }
    /* 다른 모델과의 관계 */
    static associate(db){
        db.User.hasMany(db.Comment, { foreignKey:'commenter',sourceKey:'id'});
    }
};

 

⚠️시퀄라이즈의 자료형과 MySQL의 자료형 알기

  • 테이블 칼럼 설정 옵션 (super init의 첫 번째 인수)
  MySQL Sequelize
문자열 VARCHAR(100) STRING(100)
정수 INT INTEGER
-128부터 -127까지의 정수 or 1또는 0 TINYINT BOOLEAN
날짜와 시간 정보 DATETIME DATE
0~4294967295 사이 정수* INT UNSIGNED INTEGER.UNSIGNED
빈칸 허용 여부 NOT NULL allowNull: false
값의 고유성 여부 UNIQUE unique: true
데이터의 기본값 DEFAULT now() defaultValue: Sequelize.NOW

* INT는 기본적으로 -2147483648부터 2147483647까지로 음수 범위부터 양수 범위까지 저장이 가능하나 UNSIGNED 옵션이 붙으면 음수는 무시되고 무시된 만큼 양수 범위를 늘려 저장할 수 있다.

  • 테이블 자체 설정 옵션 (super init의 두 번째 인수)
sequelize static init 메서드의 매개변수와 연결되는 옵션으로,
db.sequelize객체를 넣어야 하고, 나중에 model/index.js에서 연결
timestamps 속성이 true면 createdAt과 updatedAt을 칼럼에 추가한다.
underscored 테이블명과 컬럼명을 캐멀형(createdAt)에서 스네이크형(created_at)으로 바꾸는 옵션
modelName 모델 이름 설정
tableName 데이터베이스의 테이블 이름 설정
paranoid true 속성이면 deletedAt칼럼이 생김
(로우를 복원해야 하는 상황이 있다면 true로 설정)
charset과 collate 한글을 입력할 수 있도록 설정하는 옵션 (각각 utf8mb4, utf8mb4_general_ci로 설정)

 


    ✔️comment.js -> MySQL에서 정의한 comment 테이블을 시퀄라이즈에서도 정의하기

'use strict'

const Sequelize = require('sequelize');

module.exports = class Comment extends Sequelize.Model {
    /* 테이블에 대한 설정 */
    static init (sequelize) {
        return super.init({
            comment: {
                type: Sequelize.STRING(100),
                allowNull: false,
            },
            created_at: {
                type: Sequelize.DATE,
                allowNull: true,
                defaultValue: Sequelize.NOW,
            },
        }, {
            sequelize,
            timestamps: false,
            modelName: 'Comment',
            tableName: 'comments',
            paranoid: false,
            charset: 'utf8mb4',
            collate:'utf8mb4_general_ci',
        });
    }
    /* 다른 모델과의 관계 */
    static associate(db){
        db.Comment.belongsTo(db.User, {foreignKey:'commenter',targetkey:'id'});
    }
};

 

⚠️users와 comments 테이블 간의 관계 정의

  • 1:N 관계 > 사용자 한 명은 여러 개의 댓글을 작성할 수 있어 일대다 관계이다.
hasMany 메서드 belongsTo 메서드
users 테이블의 로우 하나를 불러올 때 comments 테이블의 로우들 부름 comments 테이블의 로우를 불러올 때 users 테이블의 해당 로우 가져옴

 

 

 

 

 

 

 

 

with Node.js 교과서

Comments