Search code examples
typeorm

TypeORM how to seed database


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?


Solution

  • 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.