TypeORM how to seed database

Aaron Ullal picture Aaron Ullal · Jul 5, 2018 · Viewed 24.8k times · Source

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?

Answer

oleh.meleshko picture oleh.meleshko · Jan 6, 2019

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:

  1. create another connection inside ormconfig.js file and specify another folder for "migrations" - in fact our seeds
  2. generate and run your seeds with -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",
  },
  ...
}