Realm 在 React Native 中插入新模式

Realm Insert New Schema in ReactNative

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) => {


            },
        });

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