领域在ReactNative中插入新模式

时间:2018-12-29 15:59:02

标签: react-native realm realm-migration

const schema1 = [

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

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

以上是两个模式Schema1是我已经在使用的模式,并且可以正常工作。Schema2是新的模式,在该模式下,我在联系模式之后在末尾添加了新表(方案)。我已经按照文档进行操作,但是找不到任何能解释在旧模式中添加新表的内容。下面是我用来初始化新架构的代码,该架构在运行时崩溃

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


            },
        });

1 个答案:

答案 0 :(得分:1)

如果要更新生产应用程序的架构。然后,您需要编写迁移逻辑并更新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;
});

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

如果您当前正在开发应用程序,则只需更新schemaVersion并添加deleteRealmIfMigrationNeeded属性即可删除旧的过时数据

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