Search code examples
typeormseeding

Is it possible to seed data only not exists with typeorm-seeding?


In ormconfig.ts, it can set seeds to point to a path for all the files.

  {
    ...
    seeds: ['db/seed/*.ts'],
  },

Is it possible to run only one file with an option like

$ npm run seed:run -f db/seed/file1.ts

In other words, if the data already been seeded into db, run it again will create duplicated data. How to avoid it?


Solution

  • I just encountered this. What I did was check first if the data exists (get the records first then loop to each record), if not, push the updates to an array. Then call insert command with the updates.

    const updates = [];
    const records = await getRecords();
    records.foreach(record => {
        if (!exists) updates.push(...);
    });
    await connection
        .createQueryBuilder()
        .insert()
        .into(TableName)
        .values(updates)
        .execute()