728x90

데이터베이스 설정하기

우선 데이터베이스는 postgresql를 사용할 것이며, 늘 그렇듯 docker 위에서 돌릴 것이다.

 

우선 테이블을 좀 만들어두고, 들어가도록 하자.

create table public.users
(
    id     uuid not null
        constraint users_pk
            primary key,
    name   text not null,
    age    integer,
    remark text
);

 

sequelize

일단 ORM의 한 종류라고 한다.

객체와 데이터베이스의 Relatiuon을 Mapping해준다.

우선 Sequelize, Postgresql 라이브러리들을 설치해주자.

{
  "name": "express",
  "version": "0.0.1",
  "type": "module",
  "description": "study express",
  "main": "dist/index.js",
  "scripts": {
    "dev": "tsx watch src/index.ts",
    "build": "tsc",
    "start": "node dist/index.js"
  },
  "dependencies": {
    "@eslint/js": "^10.0.1",
    "body-parser": "^2.3.0",
    "cookie-parser": "^1.4.7",
    "dotenv": "^17.4.2",
    "eslint": "^10.5.0",
    "eslint-config-prettier": "^10.1.8",
    "eslint-plugin-prettier": "^5.5.6",
    "express": "^5.2.1",
    "express-session": "^1.19.0",
    "morgan": "^1.11.0",
    "multer": "^2.2.0",
    "nunjucks": "^3.2.4",
    "pg": "^8.22.0",
    "pg-hstore": "^2.3.4",
    "sequelize": "^6.37.8"
  },
  "devDependencies": {
    "@types/cookie-parser": "^1.4.10",
    "@types/express": "^5.0.6",
    "@types/express-session": "^1.19.0",
    "@types/morgan": "^1.9.10",
    "@types/multer": "^2.1.0",
    "@types/node": "^26.0.1",
    "@types/nunjucks": "^3.2.6",
    "@types/pg": "^8.20.0",
    "globals": "^17.7.0",
    "prettier": "^3.8.4",
    "sequelize-cli": "^6.6.5",
    "tsx": "^4.22.4",
    "typescript": "^5.5.3",
    "typescript-eslint": "^8.62.0"
  },
  "private": true
}

 

그 다음에 다시 콘솔에

 npx sequelize init

다음과 같이 입력해주면 models,mirgrations,seeders라는 폴더들이 생긴다.

 

models의 index.ts를 다음과 같이 작성해주고

import { Sequelize } from 'sequelize';
import config from '../config/config.json' with { type: 'json' };

const env = process.env.NODE_ENV ?? 'development';

const dbConfig = config[env as keyof typeof config];

export const sequelize = new Sequelize(
    dbConfig.database,
    dbConfig.username,
    dbConfig.password ?? '',
    {
        host: dbConfig.host,
        dialect: dbConfig.dialect as 'postgres',
        logging: false,
    },
);

app.ts를 다음과 같이 수정한 후 시작해보면

import express from 'express';
import dotenv from 'dotenv';
import nunjucks from 'nunjucks';
import { sequelize } from './models/index.js';

dotenv.config();

const app = express();
app.set('port', process.env.PORT || 3000);

nunjucks.configure('views', {
    express: app,
    watch: true,
});

sequelize
    .sync({ force: false })
    .then(() => {
        console.log('connect to database');
    })
    .catch(console.error);

app.listen(app.get('port'), () => console.log('Server on'));

데이터베이스에 연결되었다고 뜨는 것을 볼 수 있다.

 

모델 정의하기

이제 저 위에 작성했던 테이블을 express의 모델로도 작성해보자.

import { DataTypes, Model, Sequelize } from 'sequelize';

export class User extends Model {
    declare id: string;
    declare name: string;
    declare age: number | null;
    declare remark: string | null;

    static initModel(sequelize: Sequelize) {
        return User.init(
            {
                id: {
                    type: DataTypes.UUID,
                    primaryKey: true,
                    allowNull: false,
                },
                name: {
                    type: DataTypes.TEXT,
                    allowNull: false,
                },
                age: {
                    type: DataTypes.INTEGER,
                    allowNull: true,
                },
                remark: {
                    type: DataTypes.TEXT,
                    allowNull: true,
                },
            },
            {
                sequelize,
                modelName: 'User',
                tableName: 'users',
                timestamps: false,
                underscored: false,
            },
        );
    }
}

여기서는 init을 사용했는데 init 메서드에서는 테이블에 대한 설정을 한다.

이제 관계를 만들어보기 위해 다음과 같은 테이블을 만들어보자.

create table public.lecture
(
    id         uuid      not null
        constraint lecture_pk
            primary key,
    user_id    uuid      not null
        constraint lecture_users_id_fk
            references public.users,
    name       text      not null,
    created_at timestamp not null
);

 

이거도 model로 정의하면

import { DataTypes, Model, Sequelize } from 'sequelize';

export class Lecture extends Model {
    declare id: string;
    declare userId: string;
    declare name: string;
    declare createdAt: Date;

    static initModel(sequelize: Sequelize) {
        return Lecture.init(
            {
                id: {
                    type: DataTypes.UUID,
                    primaryKey: true,
                    allowNull: false,
                    defaultValue: DataTypes.UUIDV4,
                },
                userId: {
                    field: 'user_id',
                    type: DataTypes.UUID,
                    allowNull: false,
                },
                name: {
                    type: DataTypes.TEXT,
                    allowNull: false,
                },
                createdAt: {
                    field: 'created_at',
                    type: DataTypes.DATE,
                    allowNull: false,
                },
            },
            {
                sequelize,
                modelName: 'Lecture',
                tableName: 'lecture',
                timestamps: false,
                underscored: true,
            },
        );
    }
}

 

이제 관계를 정의해보자, 현재 user와 lecture는 1:N의 관계이다.

 

여기서 1에 해당하는 친구가 hasMany를 통해 관계를 정의하고, N에 해당하는 친구가 belongsTo에 해당하는 관계를 정의한다.

해당 코드를 index.ts에 추가하자.

User.initModel(sequelize);
Lecture.initModel(sequelize);

User.hasMany(Lecture, {
    foreignKey: 'userId',
    as: 'lectures',
});

Lecture.belongsTo(User, {
    foreignKey: 'userId',
    as: 'user',
});

만약 1:1의 관계면 여기서 hasMany가 아닌 hasOne을 사용하며, N:M은 알아서 매핑 테이블 만들도록 하자.

 

쿼리

자 이제 모델을 모두 정의했으니 ORM을 통해 데이터베이스를 조작해보자.

 

  • insert
import { User } from "./models/user.js";

const user = await User.create({
  id: crypto.randomUUID(),
  name: "홍길동",
  age: 25,
  remark: "테스트 사용자",
});
  • select

전체조회는 그냥 다 가져오면 된다.

const users = await User.findAll();

 

가장 많이 사용하는 pk를 통한 조회는 다음과 같다.

const user = await User.findByPk("5d75d713-46bb-48fd-9a53-cbbda442ff3d");

 

조건을 많이 쓰고 싶다면 이렇게 where에 조건을 나열하면 되고

const users = await User.findAll({
  where: {
    age: 25,
    remark: "학생",
  },
});

 

하나만 조회하고 싶다면 findAll이 아닌 findOne을 사용한다.

const user = await User.findOne({
  where: {
    name: "홍길동",
  },
});
  • update

where에 조건을 작성하고, 그 위에 바꿀 값들을 작성한다.

await User.update(
  {
    age: 30,
    remark: "수정됨",
  },
  {
    where: {
      id: "사용자 UUID",
    },
  }
);

 

몇개가 업데이트 되었는지도 조회가 가능하다.

const [count] = await User.update(
  {
    age: 30,
  },
  {
    where: {
      name: "홍길동",
    },
  }
);
  • delete

삭제는 다음과 같은 코드로 작성하며

await User.destroy({
  where: {
    id,
  },
});

 

여기서도 삭제된 데이터의 개수를 알 수 있다.

const count = await User.destroy({
  where: {
    id,
  },
});

 

관계를 통해 조회하기

만약 특정 강의를 듣는 사용자를 검색하고 싶으면, join을 사용해야 한다.

강의를 조회하고, 그 안에 include로 사용자들을 넣어서 가져오면 된다.

const lectures = await Lecture.findAll({
  where: {
    name: "Express",
  },
  include: [
    {
      model: User,
      as: "user",
    },
  ],
});

'Node > Node.js' 카테고리의 다른 글

express로 mongodb 사용하기  (0) 2026.06.27
express 시작하기  (0) 2026.06.27
노드 패키지 매니저  (0) 2026.06.24
노드로 http 서버 만들어보기  (0) 2026.06.23
노드 사용해보기  (0) 2026.06.22

+ Recent posts