I am running my Node JS backend using typeorm ORM.
Coming from Entity Framework, it was very easy to seed the db with a few lines such as
Database.SetInitializer(new DbInitializer());
Where the DbInitializer class would contain all the seeding info.
Is there a similar approach to seed the database in TypeOrm? If not, what is the recommended way of doing it?
1) Create a new migration with the data insertion statements? 2) Create a task where you instantiate and save entities?
Unfortunately, there is no officially released solution from TypeORM (at the time this answer was being published).
But there is a nice workaround we can use:
ormconfig.js
file and specify another
folder for "migrations" - in fact our seeds-c <connection name>
. That's it!Sample ormconfig.js:
module.exports = [
{
...,
migrations: [
'src/migrations/*.ts'
],
cli: {
migrationsDir: 'src/migrations',
}
},
{
name: 'seed',
...,
migrations: [
'src/seeds/*.ts'
],
cli: {
migrationsDir: 'src/seeds',
}
}
]
Sample package.json:
{
...
scripts: {
"seed:generate": "ts-node typeorm migration:generate -c seed -n ",
"seed:run": "ts-node typeorm migration:run -c seed",
"seed:revert": "ts-node typeorm migration:revert -c seed",
},
...
}