播种时未找到 "entity" 的元数据

No metadata for "entity" was found when seeding

我正在使用 Faker over TypeORM 构建播种系统,在播种时抛出以下错误:

  TypeORM Seeding v1.6.1
✔ ORM Config loaded
✔ Factories are imported
✔ Seeders are imported
✔ Database connected
⠹ Executing CreateUsers Seeder
❌  Could not save entity
EntityMetadataNotFound: No metadata for "UsersEntity" was found.

✖ Could not run the seed CreateUsers!
Error: Could not save entity

error Command failed with exit code 1.

我在 package.json

中使用 typeorm-seeding npm 包的 CLI
"seed": "yarn migration:up && cross-env CLI=true ts-node -r tsconfig-paths/register ./node_modules/typeorm-seeding/dist/cli.js ---root src/core/config -n database-configuration.ts seed",

user.factory.ts 使用 users.entity.ts

define(UsersEntity, async (faker: typeof Faker) => {
  const user = new UsersEntity();
  user.firstName = faker.name.firstName();
  user.lastName = faker.name.lastName();
  user.email = faker.internet.email().toLowerCase();
  user.phone = faker.phone.phoneNumber();
  user.imageUrl = faker.image.people();
  user.password = await CryptoUtils.getHash('password');
  user.role = Role.User;
  return user;
});

然后user.seeder.ts到运行播种

export class CreateUsers implements Seeder {
  public async run(factory: Factory): Promise<any> {
    await factory(UsersEntity)().createMany(10);
  }
}

最后,这是我在 CLI 中用于 运行 播种

的数据库配置
return {
    type: 'postgres',
    host: process.env.POSTGRES_HOST,
    port: +process.env.POSTGRES_PORT,
    username: process.env.POSTGRES_USER,
    password: process.env.POSTGRES_PASSWORD,
    database: process.env.POSTGRES_DB,
    entities:
      process.env.NODE_ENV === 'test'
        ? ['src/**/*.entity.ts']
        : ['dist/**/*.entity{.ts,.js}'],
    synchronize: false,
    keepConnectionAlive: true,
    migrationsRun: true,
    logging: process.env.DATABASE_SHOW_SQL === 'true' || false,
    migrations:
      process.env.NODE_ENV === 'test'
        ? ['src/core/database/migrations/**/*.ts']
        : ['dist/core/database/migrations/**/*.js'],
    seeds: ['src/core/database/seed/seeder/**/*{.ts,.js}'],
    factories: ['src/core/database/seed/factory/**/*{.ts,.js}'],
    cli: {
      migrationsDir: 'src/core/database/migrations',
    },
};

我通过在 factoriesseeds 文件上添加 NODE_ENV 检查来解决这个问题,以避免在 distsrc.

问题是我在 development 环境中工作。这些实体是在 dist 目录而不是 factories 中找到的,而 seeds 是在 src 而不是dist 个文件夹。

解决方案是对 factoriesseeds 也应用 process.env.NODE_ENV 检查:

seeds:
    process.env.NODE_ENV === 'test'
        ? ['src/core/database/seed/seeder/**/*.ts']
        : ['dist/core/database/seed/seeder/**/*.js'],
factories:
    process.env.NODE_ENV === 'test'
        ? ['src/core/database/seed/factory/**/*.ts']
        : ['dist/core/database/seed/factory/**/*.js'],