简体   繁体   中英

NestJS - TypeORM - Unable to track the Entity Not Found in TypeOrm & Nest.JS

No repository for "UserEntity" was found. Looks like 
this entity is not registered in current "default" connection? +114ms
RepositoryNotFoundError: No repository for "UserEntity" was found. Looks like this entity is not registered in current "default" connection?
    at RepositoryNotFoundError.TypeORMError [as constructor] (E:\Projects\...\src\error\TypeORMError.ts:7:9)

This is a Seed Method. It runs fine and add the data in the database, after adding data, I just get the error.

import { MediaEntity } from '../entities/media.entity';
import { Connection, Equal } from 'typeorm';
import { UserEntity } from '../entities/user.entity';
import { Helper } from '../services/helper';

export default async function UsersSeed(connection: Connection) {
  const repository = connection.getRepository(UserEntity);

  const data: Partial<UserEntity> = {
    firstName: 'tesFName',
    lastName: 'testLNsmr',
    password: 'fafafa',
    email: 'testmail@mail.com',
    createdAt: Helper.dateToUTC(new Date())
  };

  let user = await repository.findOne({ email: data.email });

  console.log("19");
  console.log(user);

  if (!user) {
    const entity = Helper.createEntity(UserEntity, data);
    console.log("23");
    user = await repository.save(entity);
    console.log("25");
  } else {
    console.log("27");
    await repository.update(user.id, {
      firstName: data.firstName,
      lastName: data.lastName
    });

    console.log("33");
  }

  console.log("36");

  const mediaRepository = connection.getRepository(MediaEntity);
  await mediaRepository.update({ user: Equal(null) }, { user: user });

  return user;
}

A bit more context: It is being imported in app.module.ts as this.

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, 'uploads')
    }),
    TypeOrmModule.forRootAsync({
      useFactory: async (optionsService: OptionsService) =>
        optionsService.typeOrmOptions(),
      imports: [OptionsModule],
      inject: [OptionsService]
    }),
    OptionsModule,
    MediaModule,
    AuthModule,
    PlaceModule,
    RepositoryModule,
    ServicesModule
  ],
  controllers: [],
  providers: []
})

And then there is src/entities/entities.module.ts as:

const entities = [
  UserEntity,
  MediaEntity,
  PlaceEntity,
  DownloadRestrictionEntity,
  MediaInfoEntity
];

@Module({
  imports: [TypeOrmModule.forFeature(entities)],
  exports: [TypeOrmModule.forFeature(entities)]
})
export class EntitiesModule {
}

Then src/options/options.service.ts as

@Injectable()
export class OptionsService {
  constructor(
    private service: ConfigService<IEnvironmentVariables>
  ) {
  }
 public typeOrmOptions(): TypeOrmModuleOptions {
    const environment = process.env.NODE_ENV ? process.env.NODE_ENV : '';
    const directory = this.directory();
    return {
      type: 'postgres',

      host: this.service.get('POSTGRES_HOST'),
      port: this.service.get('POSTGRES_PORT'),
      username: this.service.get('POSTGRES_USER'),
      password: this.service.get('POSTGRES_PASSWORD'),
      database: this.service.get('POSTGRES_DATABASE'),
      synchronize: false,
      migrationsRun: this.service.get('RUN_MIGRATIONS'),
      keepConnectionAlive: this.isTest(),

      entities: [`${directory}/**/*.entity${environment ? '{.ts,.js}' : '{.js, .ts}'}`],

      migrationsTableName: 'migrations',
      migrations: [`${directory}/migrations/*.ts`],

      cli: {
        migrationsDir: 'src/migrations'
      }
    }
  }
}

please create UserRepository typeorm-repository-pattern Method 1:

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}
}

Method 2: use BaseRepository from typeorm-transactional-cls-hooked

@EntityRepository(UserAdminEntity)
export class UserAdminRepository extends BaseRepository<UserAdminEntity> {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM