How to seed TypeORM

sushil bansal
2 min readApr 27, 2019

There is no need for any packages. It is very straightforward. I am using it to seed my production server with some initial data like categories for posts/articles, permissions, roles etc.

1) Create a migration

typeorm migration:create -n YOUR_MIGRAITON_NAME

I am seeding default categories that are available for articles. So i created a migration

typeorm migration:create -n SeedCategory

2) Add seed data

create a folder in your server package named seeds (you can name anything) and create a file name category.seed.ts

export const CategorySeed = [
{
name: "Technology",
createdAt: `${new Date()}`,
updatedAt: `${new Date()}`
},
{
name: "Business",
createdAt: `${new Date()}`,
updatedAt: `${new Date()}`
},
{
name: "Politics",
createdAt: `${new Date()}`,
updatedAt: `${new Date()}`
},
{
name: "Sports",
createdAt: `${new Date()}`,
updatedAt: `${new Date()}`
}
];

you can add other fields depending upon your needs. If you want to have data with relations (one to many, many to one etc) then create the seeds in following way. permission.seed.ts

export const UserPermissionSeed = [
{
name: "Create Post",
description: "Create Post",
createdAt: `${new Date()}`,
updatedAt: `${new Date()}`,
enabled: true
}
];

and role.seed.ts

export const UserRoleSeed = {
name: "user",
description: "Normal User",
createdAt: `${new Date()}`,
updatedAt: `${new Date()}`,
enabled: true
};

So a Role can have many permissions. I did not create that relationship in the seeds. I will create it later on before saving the data in DB (as explained below).

3) Add seeded data to DB in migration

Example of data with relations:

import { getRepository, MigrationInterface, QueryRunner } from "typeorm";
import { UserPermissionSeed } from "../seed/permission.seed";
import { UserRoleSeed } from "../seed/role.seed";

export class SeedPermissionsAndRoles1556357483083
implements MigrationInterface {
public async up(_: QueryRunner): Promise<any> {
const permissions = await getRepository("permissions").save(
UserPermissionSeed
);
const userRoleSeed: any = UserRoleSeed;
userRoleSeed.permissions = permissions;
await getRepository("roles").save(userRoleSeed);
}

public async down(_: QueryRunner): Promise<any> {
// do nothing
}
}

First i am saving the permissions. I am assigning the returned/stored record as a relation to the parent seeded data:

userRoleSeed.permissions = permissions;

Finally store the Parent record.

4) Run the migration

You can manually run the migration (check typeORM docs for updated command):

ts-node ./node_modules/typeorm/cli.js migration:run

or alternatively when starting your server you can run migrations automatically:

const conn = await createTypeORMConn();await conn.runMigrations();

--

--