NestJS集成TypeORM连SQL Server遇User元数据未找到错误求助
解决NestJS+TypeORM连接SQL Server时的EntityMetadataNotFoundError问题
问题描述
我是NestJS新手,配置TypeORM连接SQL Server时遇到以下错误:
EntityMetadataNotFoundError: No metadata for "User" was found
应用启动正常,但调用findAll()函数时必定触发该错误,寻求解决办法。
项目文件代码
user.entity.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; @Entity('tbl_users') export class User { @PrimaryGeneratedColumn() user_id: number; @Column({ name: 'Name', length: 255 }) titleNameTH: string; @Column({ name: 'Email', length: 255 }) email: string; @Column({ name: 'Active', type: 'bit' }) active: boolean; }
myhr.module.ts
import { Module } from '@nestjs/common'; import { MyhrService } from './myhr.service'; import { MyhrController } from './myhr.controller'; import { User } from './entities/user.entity'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [TypeOrmModule.forFeature([User])], controllers: [MyhrController], providers: [MyhrService], exports: [MyhrService], }) export class MyhrModule {}
app.module.ts
@Module({ imports: [ ConfigModule.forRoot(), TypeOrmModule.forRootAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => ({ type: 'mssql', host: configService.get('DB_HOST'), port: +configService.get('DB_PORT'), username: configService.get('DB_USERNAME'), password: configService.get('DB_PASSWORD'), database: configService.get('DB_DATABASE'), entities: [__dirname + '/../entities/**/*.entity.{js,ts}'], synchronize: true, options: {trustServerCertificate: true} }), inject: [ConfigService], }), MyhrModule, ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
myhr.service.ts
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './entities/user.entity'; @Injectable() export class MyhrService { constructor( @InjectRepository(User) private readonly userRepository: Repository<User>, ) { } async findAll() { return await this.userRepository.find({take:10}); } }
错误原因
核心问题是TypeORM无法扫描到User实体的元数据。你的app.module.ts中配置的实体扫描路径__dirname + '/../entities/**/*.entity.{js,ts}'指向src/entities目录(因为__dirname对应src/app目录),但实际User实体位于src/myhr/entities目录下,路径不匹配导致实体未被加载。
解决方案
方案1:修正实体扫描路径
将app.module.ts中的entities配置改为能覆盖所有实体的路径,比如全局扫描src下的所有实体:
entities: [__dirname + '/../**/*.entity.{js,ts}'],
或者精确指定myhr模块下的实体路径:
entities: [__dirname + '/../myhr/entities/**/*.entity.{js,ts}'],
方案2:直接引入实体类
如果不想使用通配符路径,可直接在entities数组中导入并添加User实体:
// 先导入User实体 import { User } from './myhr/entities/user.entity'; // 在TypeOrm配置中修改entities entities: [User],
额外确认
- 确保User实体类已正确添加
@Entity()装饰器(你的代码已满足)。 - 确认
MyhrModule中已通过TypeOrmModule.forFeature([User])导入实体(你的代码已满足)。
内容的提问来源于stack exchange,提问作者Hikaru Shindo
相关产品推荐
相关产品推荐

