Search code examples
react-nativerealmrealm-migration

Realm Insert New Schema in ReactNative


const schema1 = [

    rolesSchema,
    userMutedInRoomSchema,
    uploadsSchema,
    usersForMentionSchema,
    contactsSchema,
];
const schema2 = [

    rolesSchema,
    userMutedInRoomSchema,
    uploadsSchema,
    usersForMentionSchema,
    contactsSchema,
    stickersPackagesSchema,
    stickersCollectionSchema
];

Above are the two schemas Schema1 is the one i am using already and it is working fine Schema2 is the new schema in which i have added new tables(schemas) at the end after contacts schema. I have followed the documenntation but i couldn't find anything that explains adding new tables in the old schema . Below is the code i am using to initialize new schema which crashes on run time

const path = database.replace(/(^\w+:|^)\/\//, '');
        return this.databases.activeDB = new Realm({
            path: `${ path }Value.realm`,
            schema:schema2,
            schemaVersion:1,
            migration: (oldRealm, newRealm) => {


            },
        });

Solution

  • if you are updating the schema of a production app. Then you need to write the migration logic and update the schemaVersion.

    Realm.open({
      schema: [PersonSchema],
      schemaVersion: 1,
      migration: (oldRealm, newRealm) => {
        // only apply this change if upgrading to schemaVersion 1
        if (oldRealm.schemaVersion < 1) {
          const oldObjects = oldRealm.objects('Person');
          const newObjects = newRealm.objects('Person');
    
          // loop through all objects and set the name property in the new schema
          for (let i = 0; i < oldObjects.length; i++) {
            newObjects[i].name = oldObjects[i].firstName + ' ' + oldObjects[i].lastName;
          }
        }
      }
    }).then(realm => {
      const fullName = realm.objects('Person')[0].name;
    });
    

    Refer: https://realm.io/docs/javascript/latest/#performing-a-migration

    If you are currently developing the app, then you can just update the schemaVersion and add the deleteRealmIfMigrationNeeded property to delete old stale data

    Refer: https://realm.io/docs/javascript/latest/#opening-realms