While working on a seeding system using Faker with TypeORM, I encountered an error during seeding:
🌱 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.
The seeding process is being done through the CLI of the typeorm-seeding
npm package specified in my package.json
"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",
I have a user.factory.ts
file linked with the users.entity.ts
file
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;
});
Additionally, the user.seeder.ts
file is responsible for handling the seeding process
export class CreateUsers implements Seeder {
public async run(factory: Factory): Promise<any> {
await factory(UsersEntity)().createMany(10);
}
}
Lastly, here is the database configuration used for executing the seeding process via the 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',
},
};