에러 메세지

#입력값
{ title: 'test posting4', content: 'nothing', categoryId: 1, hashtag: 'test' }

Executing (95522a76-98e3-47e9-9e38-97e9a7db1ed0): START TRANSACTION;
Executing (95522a76-98e3-47e9-9e38-97e9a7db1ed0): SELECT `id`, `word`, `created_at` AS `createdAt`, `updated_at` AS `updatedAt` FROM `hashtags` AS `hashtags` WHERE `hashtags`.`word` = 'test' LIMIT 1;
null
Executing (95522a76-98e3-47e9-9e38-97e9a7db1ed0): INSERT INTO `hashtags` (`id`,`word`,`created_at`,`updated_at`) VALUES (DEFAULT,?,?,?);
Executing (95522a76-98e3-47e9-9e38-97e9a7db1ed0): ROLLBACK;

# 실패한 쿼리 (Error 메세지에서 )
at async posts.create (/Users/joey/WebstormProjects/practice_DB_ORM_API/node_modules/sequelize/lib/model.js:1362:12) { sql: 'INSERT INTO `posts` (`id`,`title`,`content`,`created_at`,`updated_at`,`category_id`) VALUES (DEFAULT,?,?,?,?,?);' }

<추측>

1. 아마도 카테고리가 이미 생성되지 않은 상태에서  categoryId를 주어서 그럴까?

-> category를 먼저생성해서 확인 절차 코드를 추가하기 (이 부분에서 에러가 발생한 것이 맞다.)

 

<해결>

1. category를 먼저 생성

- 이 부분에서 저번에 했던 실수가 반복됨 : body 에서 { "category": "IT"}를 전달했는데 키를 동일하게 입력하지 않아서 오류 또 발생

const {newCategory } = req.body;

 

2. post를 게시(Post)할 때 category에 존재하는 id를 넘겨 줄것. 

 

* 추가적으로 transaction 에서 데이터와 관련된 작업을 순차적으로 진행되도록 관련된 코드앞에 await를 꼭 붙일 것

// 여기에서 await를 넣지 않음
const post = await Post.create(...)

 

>>> 내가 Post-Category 간의 관계를 설정해 두어서 새로운 Post를 생성할 때 Sequelize 에서 자동으로 주어진 categoryId 가 존재하는지 확인과정을 거쳤고, 그 결과 임의로 준 categoryId 가  Category에 존재하지 않아서 에러를 발생함. 

# 에러를 찾다가 발견한 것들

< 두 개의 table 을 연결해주는 모델을 만들때 좀더 명확하게 하는 것이 좋다.>

const PostHashtag = sequelize.define('post_hashtag', {
    id :{
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    postId:{
        type: DataTypes.INTEGER,
        // 명확하게 하기 위해 추가된 코드
        references:{
            model:'posts',
            key: 'id'
        }
    },
    hashtagId:{
        type: DataTypes.INTEGER,
        // 명확하게 하기 위해 추가된 코드
        references: {
            model:'hashtags',
            key:'id'
        }
    },
},{
    underscored:true
})

 

< transaction 내에서 수행한 각 쿼리의 결과를 수행하고 나면 꼭 해당 메서드를 트랜잭션에 보내서 오류가 발생하는지 파악하기>

// 예를 들어서 { transaction: t } 을 추가
const post = await Post.create({
    title,
    content,
    createdAt: new Date(),
    categoryId
    }, { transaction: t }
);
            
await post.addHashtag(existingHashtag, { transaction: t });

 

<아래의 코드 한 줄로 Post 와 Hash의 관계를 설정해주기 위해 만든 PostHashtag 에 자동으로 입력되는 것이 신기하다. >

await post.addHashtag(existingHashtag, {transaction:t});

+ Recent posts