Search code examples
nestjstypeormdata-migration

How to add a new non-null column to an existing typeORM entity in Nestjs


I want to add a new non-null column ("department" for example) to an existing entity ("employee" for example). The "employee" table already contains data, when run "$ nest start", I got the following error -

QueryFailedError: column "department" contains null values at QueryFailedError.TypeORMError [as constructor] (E:\repo\todo-js\src\error\TypeORMError.ts:7:9)

I tried to use typeORM migration to add a nullable "department" column and fill in data beforehand but turns out migration take place after typeORM data schema update when "$ nest start" is run. As such I got the above error even after I created the migration. Please note that I do not want to add a default value to the "department" column's definition as new employee insertion should specify the employee's department. How can I proceed with that? Thanks

(Part of the accepted answer is included in the comments below, you better read it all.)


Solution

  • I see at least three ways:

    1. Create nullable department column, fill it with existing data and then make it non-nullable;
    2. Create department column with empty DEFAULT value, fill it with data and then remove DEFAULT;
    3. Create new employee_new table with department column, fill it with data, remove old employee table and rename employee_new to employee.