NestJS使用TypeORM提示EntityMetadataNotFoundError找不到User元数据求助
解决方案
1. 修正TypeORM配置错误
你当前app.module.ts中的TypeORM配置存在两处明显问题:一是migrations参数没有使用join拼接路径,二是通配符匹配实体容易因编译后目录结构异常导致加载失败,建议直接使用已导入的实体对象替代路径匹配,同时开启Nest提供的自动加载实体配置:
修改TypeOrmModule.forRootAsync的返回配置如下:
return { type: 'postgres', host: configService.get('DB_HOST'), port: Number(configService.get('DB_PORT')), username: configService.get('DB_USERNAME'), password: configService.get('DB_PASSWORD'), database: configService.get('DB_DATABASE'), // 直接传入已导入的实体,比通配符匹配稳定性更高 entities: [User, Review, Rent, Item, Category], // 修正migrations路径写法 migrations: [join(__dirname, 'migrations/**/*{.ts,.js}')], synchronize: false, // 开启自动加载实体,Nest会自动识别所有通过TypeOrmModule.forFeature注册的实体 autoLoadEntities: true, cli: { entitiesDir: 'src/entities', migrationsDir: 'src/migrations', }, };
同时给ConfigModule.forRoot添加全局配置,避免跨模块注入配置时出现异常:
ConfigModule.forRoot({ envFilePath: '.env', validationSchema: configValidationSchema, // 新增全局配置,所有模块无需额外导入即可使用ConfigService isGlobal: true, })
2. 适配TypeORM版本的Repository写法
如果你的TypeORM版本为0.3.x及以上,@EntityRepository装饰器已经被官方废弃,会导致实体元数据识别失败,需要调整Repository逻辑:
- 移除
UsersRepository上的@EntityRepository(User)装饰器,给类添加@Injectable()装饰器 - 修改
auth.module.ts的TypeOrmModule.forFeature配置,直接传入User实体:
TypeOrmModule.forFeature([User])
- 调整UsersRepository内部逻辑,使用
@InjectRepository注入实体仓库:
import { Injectable, ConflictException, InternalServerErrorException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { SignUpDto } from './dto/signup.dto'; import { User } from '../entities/user.entity'; import * as bcrypt from 'bcrypt'; @Injectable() export class UsersRepository { constructor( @InjectRepository(User) private readonly userRepo: Repository<User> ) {} async createUser(signUpDto: SignUpDto): Promise<void> { const { name, surname, street, city, zip, rating, phone, date, email, password, } = signUpDto; const salt = await bcrypt.genSalt(); const hashedPassword = await bcrypt.hash(password, salt); const user = this.userRepo.create({ name, surname, street, city, zip, rating, phone, date, email, password: hashedPassword, }); try { await this.userRepo.save(user); } catch (error) { if (error.code === '23505') { throw new ConflictException('User with the same e-mail already exists'); } else { console.log(error); throw new InternalServerErrorException(); } } } }
如果你使用的是TypeORM 0.2.x版本可以跳过本步骤,只需确认User实体文件名是否为user.entity.ts,路径和导入语句是否匹配即可。
3. 检查tsconfig基础配置
确认项目根目录tsconfig.json中已经开启装饰器相关配置(NestJS默认项目会自带,如自行修改过需要补全):
{ "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, // 其余原有配置保持不变 } }
完成以上修改后重新启动项目即可解决该报错。
内容的提问来源于stack exchange,提问作者Marko Marchisio
相关产品推荐
相关产品推荐

