NestJS + TypeORM: Relation 설정 실수로 인한 user가 null인 문제 해결
NestJS 프로젝트를 하면서 post.user.user_id
를 읽으려고 했더니, TypeError: Cannot read properties of undefined
라는 오류를 마주했습니다.
왜 user
가 undefined일까요?
이번 글에서는 TypeORM에서 관계 설정 시 했던 실수를 기록하고 해결방법을 적어보겠습니다.
[Nest] ERROR [ExceptionsHandler] TypeError: Cannot read properties of undefined (reading 'user_id')
at PostService.getPostDetail (src/post/post.service.ts:223:21)
위와 같은 에러가 발생했습니다.
PostgreSQL
에서는 User
테이블에 user_id
라는 컬럼으로 들어있고, NestJS
에서 엔티티를 매핑할 때는 User 객체
로 매핑했기 때문에 user_id
가 자꾸 null
로 들어가는 문제가 발생했습니다.
엔티티 설정
@Entity('Post')
export class Post {
@PrimaryGeneratedColumn({ type: 'bigint' })
post_id: number;
@Column()
user_id: number; // DB에는 이 값이 저장됨
@ManyToOne(() => User, (user) => user.posts, { eager: false })
@JoinColumn({ name: 'user_id' }) // 외래키 컬럼 명시
user: User;
}
DB에는 user_id
숫자형 외래키 컬럼이 저장되지만, User 객체 형태로 접근하고 싶어서 user_id
컬럼은 제거하고, join 컬럼만 남겨두겠습니다.
이렇게 하면, post.user.nickname
처럼 사용자 정보에 바로 접근 가능해집니다.
@JoinColumn({ name: 'user_id' })
TypeORM
에게 "이 필드(user_id)를 외래키로 사용해서 user 객체와 연결하라" 라고 알려줍니다.- 이걸 생략하면
TypeORM
은 자동으로 이름을 추측하거나 제대로 연결하지 못해 user가 null이 되는 경우가 있습니다.
하지만, 저는 엔티티에 관계설정까지 마쳤는데 자꾸 user_id 를 불러올 수 없어서 null 이 되는 문제를 마주했습니다.
// 예시 서비스 코드
const post = await this.postRepo.findOne({
where: { post_id: 1 },
relations: ['user'],
});
relations 에 'user' 를 설정해주어야 자동으로 Post 와 연결된 User 데이터를 함께 불러올 수 있습니다.
relations가 필요한 이유
const post = await this.postRepo.findOne({ where: { post_id: 1 } });
// post.user === undefined
기본적으로 TypeORM은 관계 데이터를 자동으로 로딩하지 않습니다.
즉, 별도로 설정을 하지 않았을 경우, post.user는 undefined로 들어옵니다
relations 를 설정하면 문제없이 User 객체를 불러올 수 있습니다.