How do I insert calculated data into a database with TypeORM migrations?

Viewed 4993

I have a situation where i need to add a new column to an existing table in TypeORM. I set the column to 'nullable' as there are existing items in the table which need to have the data for that column added before I can set the column to non-nullable.

I have been trying to write a migration file to insert data into the new column for each row in the table, but it does not appear to be saving.

This is what I am trying right now:

import { MigrationInterface, QueryRunner } from 'typeorm';
import { Customer } from '../../entities';
import { generateUrlName } from '../../entities/Customer';

export class fixUrlNameCustomers1584393813738 implements MigrationInterface {
  name = 'fixUrlNameCustomers1584393813738';

  public async up(queryRunner: QueryRunner): Promise<void> {
    const customers = await queryRunner.manager.find(Customer);

    const updatedCustomers = customers.map(customer => {
      customer.url_name = generateUrlName(customer.name);
      return customer;
    });

    await queryRunner.manager.save(updatedCustomers);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {}
}

As you can see, I am trying to fill in the '.url-name' for each customer using a function called generateUrlName. After I run this migration and execute a query from Postgres I can see the migration isn't saving the data.

0 Answers
Related