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

Viewed 2695

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.

2 Answers

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.

I use migrations for this purpose. We can write static query or we can also load data from CSV and then save it in DB in a loop.

you can create an empty migration with npx typeorm migration:create -n InsertMasterDataInDB

and then you can use below query to insert data

await queryRunner.manager.query(INSERT QUERY HERE IN SINGLE QUOTES);

and then npx typeorm migration:run

Related