해결된 질문
작성
·
147
0
안녕하세요.
TypeORM 마이그레이션 실습에서 아래와 같은 typeorm.ts 파일을 작성했습니다.
import { registerAs } from '@nestjs/config';
import { DataSource, DataSourceOptions } from 'typeorm';
const config = {
type: 'postgres',
host: `${process.env.DB_HOST || 'localhost'}`,
port: parseInt(`${process.env.DB_PORT || '5432'}`, 10),
username: `${process.env.DB_USERNAME || 'test'}`,
password: `${process.env.DB_PASSWORD || 'test'}`,
database: `${process.env.DB_DATABASE || 'inflearn'}`,
entities: ['dist/**/**/*.entity{.ts,.js}'],
migrations: ['dist/migrations/*{.ts,.js}'],
autoLoadEntities: true,
synchronize: false,
};
export default registerAs('typeorm', () => config);
export const connectionSource = new DataSource(config as DataSourceOptions);
이 때, autoLoadEntities: true
항목이 있음에도, entities: []
항목이 있어야 할 필요가 있나요? 없어도 코드 동작에 차이가 없는 것인가요?
앞선 강의에서 autoLoadEntities: true
인 경우, entities: []
를 따로 설정하지 않아도 된다는 내용이 있었던 것 같아서 헷갈립니다.
감사합니다.
답변 1
0
안녕하세요! 좋은 질문 감사합니다 😊
결론부터 말씀드리면,
✅ autoLoadEntities: true를 사용하는 경우, entities는 NestJS 애플리케이션 내에서 실행할 때는 생략 가능합니다.
❗ 하지만 typeorm CLI나 DataSource를 사용하는 마이그레이션 실행 시에는 entities가 필수입니다.
autoLoadEntities: true는 NestJS 런타임 환경에서만 작동합니다.
TypeOrmModule.forFeature()로 등록된 엔티티들을 자동으로 감지합니다.
이는 NestJS의 DI 컨테이너를 활용하기 때문에 NestJS 앱 실행 시에만 적용됩니다.
반면, typeorm CLI나 DataSource를 직접 사용할 때는 Nest 컨텍스트가 없기 때문에,
const connectionSource = new DataSource(config);
이 config에 entities 배열이 명시적으로 있어야 마이그레이션이 정상 작동합니다.
결론적으로
autoLoadEntities: true → NestJS 앱 실행 시 유용
entities: ['dist/**/*.entity{.ts,.js}'] → 마이그레이션 및 CLI 명령 실행 시 필수
따라서 autoLoadEntities: true와 entities: [...]를 함께 사용하는 것이 실전에서는 안전한 조합입니다. 특히 저희처럼 typeorm 마이그레이션을 사용하고 있다면 entities를 생략하지 않아야 정상동작을 합니다. 이해 되셨을까요?
이해되었습니다. 완벽한 답변 감사합니다!