TypeORM how to seed database

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",
  },
  ...
}

I would love to see such functionality as well (and we're not alone), but at the moment, there's no official feature for seeding.

in lack of such a built-in feature, I think the next best thing would be to create a migration script named 0-Seed (so it precedes any other migration scripts you might have) and have the seed data populated there.

@bitwit has created a snippet that may come in handy for you; it's a function that reads the data from yaml files, which you can incorporate in the seed migration script.

after some research, however, I found another interesting approach: bind an after_create event to the table, and initialize the data in the listener.
I haven't implemented this, so I'm not sure it can be done directly with TypeORM.