Dandy Now!
  • [Sequelize] Sequelize timestamps의 updatedAt 업데이트, 왜 안될까?
    2025년 03월 26일 19시 20분 12초에 업로드 된 글입니다.
    작성자: DandyNow
    728x90
    반응형

    Sequelize timestamps의 updatedAt 업데이트, 왜 안될까?

    Node.js에서 Sequelize를 사용할 때 timestamps: true 옵션은 createdAtupdatedAt 컬럼을 자동으로 관리해주는 편리한 기능이다. 하지만, 때로는 예상치 못한 동작으로 인해 updatedAt이 업데이트되지 않는 상황을 마주할 수 있다. 특히, 레코드에 변경된 컬럼이 없을 경우 이러한 문제가 발생한다.

    1. 문제 상황

    다음과 같은 간단한 모델을 예시로 들어보겠다.

    const Sequelize = require("sequelize");
    module.exports = function (sequelize, DataTypes) {
      return sequelize.define(
        "Student",
        {
          id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true,
          },
          student_number: {
            type: DataTypes.STRING(20),
            allowNull: false,
          },
        },
        {
          timestamps: true,
          createdAt: "createdAt",
          updatedAt: "updatedAt",
        }
      );
    };

    REST-API를 통해 받아온 데이터를 이 테이블에 업데이트할 때, student_number가 이미 존재하는 경우 updatedAt만 현재 시간으로 수정하고자 하였다. 하지만, Sequelize는 레코드에 변경된 컬럼이 없을 경우 updatedAt을 업데이트하지 않았다.

    2. 해결 방법: status 컬럼 활용

    이 문제를 해결하기 위해 status 컬럼을 추가하고, 신규 레코드 생성 시 "created", 기존 레코드 업데이트 시 "updated" 값을 저장하였다. 이렇게 하면 Sequelize는 status 컬럼의 변경을 감지하여 updatedAt을 업데이트한다.

    const Sequelize = require("sequelize");
    module.exports = function (sequelize, DataTypes) {
      return sequelize.define(
        "Student",
        {
          id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true,
          },
          student_number: {
            type: DataTypes.STRING(20),
            allowNull: false,
          },
          status: { // status 컬럼 추가
            type: DataTypes.STRING(10),
            allowNull: true,
          },
        },
        {
          timestamps: true,
          createdAt: "createdAt",
          updatedAt: "updatedAt",
        }
      );
    };
    
    // ... REST-API 데이터 처리 로직 ...
    
    if (existingStudent) {
      await Student.update(
        {
          status: "updated", // status 컬럼 업데이트
        },
        { where: { student_number: student_number } }
      );
    } else {
      await Student.create({
        student_number: student_number,
        status: "created", // status 컬럼 초기화
      });
    }

    3. Sequelize timestamps의 특징

    Sequelize의 timestamps 옵션은 레코드의 변경 여부를 감지하여 updatedAt을 업데이트한다. 따라서, 특정 컬럼의 값만 변경하더라도 Sequelize는 해당 레코드를 변경된 것으로 인식하고 updatedAt을 업데이트한다. 하지만, 레코드에 변경된 컬럼이 없을 경우 updatedAt은 업데이트되지 않는다.

    4. 결론

    Sequelize의 timestamps 옵션을 사용할 때, updatedAt이 예상대로 업데이트되지 않는 경우 status와 같은 상태 관리 컬럼을 활용하여 문제를 해결할 수 있다.

    728x90
    반응형
    댓글