I am starting to study typeorm and I am confused about what happens if I add a new column to an existing entity that was already persisted with data. I use SQlite.
I saw in the documentation, in the "Migrations" section, it looks like there is a procedure that must be done if I want to add a new column.
But when I saw this issue in typeorm's github, I understood that if I just add the new "@Column" annotated property to the Entity class would be enough and typeorm would create the column automatically when the app starts.
I was really hoping that typeorm would be able to handle that schema change automatically.
Can someone help?
TypeOrm is capable of changing the schema but is does not run migrations automatically on server start (this is not a wanted behaviour). If you want the migrations to be executed when the app the starts you need to todo the following to steps:
After changing your entity (like adding a new column) you need to generate a migration file:
typeorm migration:generate -c 'connectionName'
That migration file is then created into a folder configured in your ormconfig.json.
Before you start your server, you need to create the database connection and run the migrations. So your main file should look like
import { Connection, getConnectionManager } from 'typeorm';
const connectionManager = getConnectionManager();
const connection = connectionManager.get(connectionName);
await connection.runMigrations();
// start your server
startServer();
For development purpose you can also use schema synchronization, in that case typeorm syncs your database with your entity:
npx typeorm schema:sync -c 'connectionName'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With