Loopback 3 updating model properties ensure old data is converted correctly without data loss

116 Views Asked by At

So I am using Loopback 3 atm, and I am currently updating the properties of my model. Problem is that the structure will be different as before as certain properties are now split into 2 separate properties, thus if I would place it online that data might be lost due to those changes. (I am using mongodb)

Example original structure:

{
  "properties": {
    "address": {
      "type": "string"
    }
  }
}

Example new structure:

{
  "properties": {
    "address": {
      "type": {
        "street": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "zipcode": {
          "type": "string"
        }
      }
    }
  }
}

In my case there are also properties that change names instead of address its addressline or something like that.

I know that some of you might say that its better to move address to a separate model but this is just an example in my case im unable to move it to a separate table due to certain circumstances.

So my question is how can you update a model and remap the existing data to follow the new structure to ensure that the original data isn't lost.

Thanks in advance!

1

There are 1 best solutions below

0
On

Here's my answer

I understand that loopback is database independent and my approach is going against that, nevertheless here's my approach.

We can write migration script based on the underlying db, this is what I tried for postgresdb

#1 For the scenario where data type is being changed.

 ALTER TABLE dbname ADD COLUMN address2 jsonb;
 UPDATE dbname set address2= to_json(address) ;
 ALTER TABLE dbname DROP COLUMN address;
ALTER TABLE dbname RENAME COLUMN address2 TO address;

#2 and for the scenario where name needs to be changed

 ALTER TABLE dbname ADD COLUMN addressline jsonb;
 UPDATE dbname set addressline= address;
 ALTER TABLE dbname DROP COLUMN address;

Hoping to find more and better answer for this question!!