node.jspostgresqldatabase-migrationloopbackjsloopback

Set new fields' value after database migration in LoopBack 4


Loopback has an easy way to deal with database migrations, which differs from the method that uses, for example, knex.js. In the docs about migration it says that in order to mutate table's schema you just have to edit your models, and Loopback will automatically update (in case of Auto-update) or recreate (in case of Auto-migrate) the tables.

But here is a situation: Suppose I have a project which is in production. In the database I have a table users with fields:

first_name: string
last_name: string

Then I want to change my schema to

full_name: string

In the case of Loopback to gain this schema i just have to edit the model. But how do I set full_name for existing users? The method described in docs confuses me, and here is why:

Its working if I create field-updating script (also removing the previous ones to avoid errors) and run the migration after every change in my models.

But what if I have to do several migrations (also scripts that set new values) in my local environment before deploying to production?

Thanks for your help.


Solution

  • The automatic update/recreate functionality offered by LoopBack will be always limited to simple use cases like adding new columns. Once you need to migrate a more advanced schema change, e.g. renaming a column, you will always have to write a custom migration step - and that's where Knex shines from what I've been told.

    We are aware of the problem and have been discussing it in the following issue - feel free to join the discussion!

    Its working if I create field-updating script (also removing the previous ones to avoid errors) and run migration after every change in my models.

    But what if I have to do several migrations (also scripts that set new values) in my local environment before deploying to production?

    Personally, I have had great experience with Evolutionary Database Design, where each migration step is assigned a unique change id and there is a new table keeping track of changes/migration applied.