Search code examples
nestjstypeorm

Nest/TypeORM: Adding foreign key column after relationship has previously been defined wipe out data


This might be the case when I have to write manually the migration files to do migration. But still, I still wish someone might know the answer.

This is related to the question I asked earlier which is solved but dealing with creating the model , not changing model which is this one.

How to expose foreign key column in the entity in TypeORM

So, when defining entity, you can set foreignKeyID as one column, then foreignKeyEntity as another join column. That's very OK.

But TypeORM can automatically add the foreignKeyID column if you don't explicitly have it. Yet I found it is super convenient to have the foreignKey in the data model. So I want to add it. But by the time, the table has data in it.

Current relation column user in Model definition

@ManyToOne(type => User)
@JoinColumn({ name: 'user_id' })
user: User;

Added userId the column

@Column({ name: 'user_id' })
userId: string;

@ManyToOne(type => User)
@JoinColumn({ name: 'user_id' })
user: User;

The moment Nest starts, the foreign key column is wiped out clean.

Because I am using the auto-migrate ( database sync ) the development ENV provides. I am using NestJS. So I think it is hard to understand what is going on here. Might be that I need to go through TypeORM document and take the time to write migration in the right way, make sure data will be retained.

But still just in case someone knows how.

PLUS: set nullable will wipe clean with default NULL value.

@Column({ name: 'user_id', nullable: true })
userId: string;

Solution

  • I suggest the following. Trying to analize, how the auto-migrate works is a waste of time for 2 reasons:

    • This feature is only useful for experimental development, or when you create the entity-relationship model. If you already have a production database, you can forget it, since its mechanism is not predictable, and not for production environment.
    • In the end, you'll definitely need migrations to keep up with the changes in production. This is the only long-term solution.

    What I suggest is to disable auto-migrate and use migration files to preserve the state of your database. The earlier you adopt this approach, the less painful. Since TypeORM has tools to generate migrations automatically, it is not event a painful job, just execute the following command:

    typeorm migration:generate --name <migration_name>
    

    I know, you'll have some work with this, but with this change, adding new features to your database incrementally is going to be easy, elegant and safe. I always use migrations on my work projects from the beginning.