当前位置: 首页 > 知识库问答 >
问题:

TypeOrm: RepositoryNotFoundError在NestJS播种时

关翰
2023-03-14

我正在尝试使用NestJS和TypeORM为我的数据库设置种子。

我有一个迁移文件,它创建了一个练习表,还有一个种子文件,它将一个练习插入到表中。这些文件的主要区别是迁移文件直接运行查询:

public async up(queryRunner: QueryRunner): Promise<any> {
  await queryRunner.query(
    `CREATE TABLE ...`
  );
}

当种子文件获取存储库时:

public async up(queryRunner: QueryRunner): Promise<any> {
  await queryRunner.manager.getRepository<ExerciseEntity>(ExerciseEntity).save(
    someExerciseEntity
  );
}

这个getRepository是产生错误的那个。

RepositoryNotFoundError: No repository for "ExerciseEntity" was found. Looks like this entity is not registered in current "default" connection?
    at new RepositoryNotFoundError (C:\Users\Dev\Documents\team-management\src\error\RepositoryNotFoundError.ts:10:9)
    at EntityManager.getRepository (C:\Users\Dev\Documents\team-management\src\entity-manager\EntityManager.ts:1194:19)
    at SeedExercises1584903747780.<anonymous> (C:\Users\Dev\Documents\team-management\dist\apps\api\_seeds\dev\webpack:\_seeds\dev\1584903747780-SeedExercises.ts:7:31)

在一个服务中,我获得了存储库并保存了实体,没有任何问题。问题只在播种时发生。

我注册打字格式如下:

// app.module.ts
@Module({})
export class AppModule implements NestModule {
  static forRoot(): DynamicModule {
    return {
      module: AppModule,
      imports: [
        ConfigModule.forRoot({
          envFilePath: '.env.dev',
          validationSchema: validationSchema()
        }),
        TypeOrmModule.forRootAsync({
          imports: [ConfigModule],
          inject: [ConfigService],
          useFactory: async (configService: ConfigService) => databaseProviders(configService)
        }),
        ExercisesModule.forRoot()
      ]
    };
  }
}

哪里:

// database.provider.ts
export const databaseProviders = (configService: ConfigService) => {
  const normalizePath = (_path: string) => (path.normalize(path.join(__dirname, _path)));

  const commonDB: TypeOrmModuleOptions = {
    type: 'sqlite',
    entities: [...exercisesEntities]
  };
  // exerciseEntities comes from an index.ts in an exercise library
  // import { ExerciseEntity } from './exercise.entity';
  // export const exercisesEntities = [ExerciseEntity];

  const defaultDB: TypeOrmModuleOptions = {
    ...commonDB,
    database: path.join(
      configService.get('APP_ROOT_PATH', '.'),
      configService.get('TYPEORM_DATABASE', 'gym-dev.sqlite')
    ),
    logging: configService.get<boolean>('TYPEORM_ENABLE_LOGGING', true) ? ['query', 'error'] : [],
    cache: true,
    synchronize: configService.get<boolean>('TYPEORM_SYNCHRONIZE', false),
    migrations: [normalizePath('_migrations/*.js'), normalizePath('_seeds/dev/*.js')],
    migrationsRun: configService.get<boolean>('TYPEORM_MIGRATIONS_RUN', true),
    dropSchema: configService.get<boolean>('DROP_SCHEMA', false)
  };

  return defaultDB;
};

我正在使用nrwl/nx使用以下网页配置编译和服务应用程序:

module.exports = function(config, context) {
  const baseDirectory = path.resolve(config.output.path);

  const entityPaths = ['libs/feature/api/**/entities/*.js'];
  const migrationPaths = ['_migrations/*.js', '_seeds/**/*.js'];
  config.entry = {
    ...config.entry,
    ...getEntityEntries(entityPaths),
    ...getMigrationEntries(migrationPaths)
  };
  // getEntries functions allows the compilation of entities and migrations

  // Output
  config.output = {
    path: baseDirectory,
    filename: '[name].js',
    libraryTarget: 'commonjs'
  };

  return config;
};

我的dist结构最终是:

dist
|-apps
  |-api
    |-_migrations  // contains compiled migrations
    |-_seeds       // contains compiled seeders
    |-lib
      |-entities   // contains compiled entities
    |-main.js

正如在app.module.ts中看到的,我正在使用TypeOrmModule.forRootAsync来注入配置服务。我怀疑也许当种子被执行时,存储库还没有注册。这就解释了,在运行Web应用程序时,服务可以访问存储库。

你知道我该怎么解决这个问题吗
我的配置是否错误或缺少什么?如果问题出在播种机中,是否有办法等待存储库注册?

编辑:
它与TypeOrmModule没有任何关系。forRootAsync。我做了以下更改:

// app.module.ts
@Module({})
export class AppModule implements NestModule {
  static forRoot(): DynamicModule {
    return {
      module: AppModule,
      imports: [
        ConfigModule.forRoot({
          envFilePath: '.env.dev',
          validationSchema: validationSchema()
        }),
        TypeOrmModule.forRoot(databaseProvidersSync()),
        ExercisesModule.forRoot()
      ]
    };
  }
}
// database.providers.ts
export const databaseProvidersSync = () => {
  const normalizePath = (_path: string) => (path.normalize(path.join(__dirname, _path)));
  const defaultDB: TypeOrmModuleOptions = {
    type: 'sqlite',
    entities: [...exercisesEntities],
    database: path.normalize(`C:\\Users\\Dev\\Documents\\team-management\\gym-dev.sqlite`),
    logging: ['query', 'error'],
    cache: true,
    synchronize: false,
    migrations: [normalizePath('_migrations/*.js'), normalizePath('_seeds/dev/*.js')],
    migrationsRun: true,
    dropSchema: true
  }

  return defaultDB;
}

错误是一样的。

共有1个答案

夏元明
2023-03-14

问题来自当前的TypeORM版本(0.2.24)。

我切换到0.2。22它成功了,没有改变其他任何东西。

这是我用这篇文章开始的问题,最后问他们什么时候能解决这个问题:https://github.com/typeorm/typeorm/issues/5781
这里有一些问题似乎在上一版本中讨论了这个问题:
https://github.com/typeorm/typeorm/issues/5676

 类似资料:
  • 本文向大家介绍arduino 播下种子,包括了arduino 播下种子的使用技巧和注意事项,需要的朋友参考一下 示例 如果重要的是要由生成的数字序列random()不同,则最好使用以下代码指定种子randomSeed():            

  • A collection of Badass modules and utilities to help you level up your NestJS application. Package Description Version Changelog @golevelup/nestjs-common Common types, mixins changelog @golevelup/nest

  • 嗨,我有以下种子类我试图种子。当我运行php artisan db:种子命令时,唯一的种子是我几周前创建的上一个种子类。我不知道我错过了什么。我还插入了SoftDeletes和受保护的可填充内容。 这是我的播种课: 我的模型:

  • Description The rbac module for Nest. Installation npm i --save nestjs-rbac Quick Start For using RBAC there is need to implement IStorageRbac export interface IStorageRbac { roles: string[]; permis

  • Nestjs-BFF OVERVIEW Overview     Frontend     Backend     CLI     DevOps Status This library is currently 'on ice' and is no longer being activley maintained at this time. However, it may still server

  • rucken-core-nestjs A simple application demonstrating the basic usage of permissions with NestJS (JWT, Passport, Facebook, Google+, User, Group, Permission) based on Rucken template Screenshots Featur