Search code examples
typescriptnestjstypeorm

TypeORM insert basic master data (types, status,..) after creating the table


I have question for you. I am using NestJS and typeORM. I am trying to insert default values to tables after creating the tables. For example i have a priority table and i need to insert High/Medium/Low values. I tried everything from typeorm and nestJS documentation and I read related questions and answers from here. I could not do it yet.

import {getConnection} from "typeorm";

await getConnection()
    .createQueryBuilder()
    .insert()
    .into(User)
    .values([
        { firstName: "Timber", lastName: "Saw" }, 
        { firstName: "Phantom", lastName: "Lancer" }
     ])
    .execute();

I have found above code and i think the way is this. But i could not find in which file should i use this code chunk. If you help me i will be very happy. Thanks.


Solution

  • You can use migrations to keep your database up to date. They can be used not only to modify tables, but also to add default data. TypeORM has a mechanism for doing this.