-1

我在 realm.js 文件中有以下 2 个模式

    class Bill extends Realm.Object {}
        Bill.schema = {
          name: 'Bill',
          primaryKey: 'id',
          properties: {
            id: { type: 'string', indexed: true },
            year: 'int',
            month: 'int',
            description: 'string',
            dateCreated: 'int',
        }
    };

    class User extends Realm.Object {}
        User.schema = {
          name: 'User',
          primaryKey: 'id',
          properties: {
            id: 'string',
            name: 'string?',
            email: 'string?'
          }
    };

 const realm = new Realm({schema: [Bill, User]}); 

 export default realm;

当我第一次将我的应用程序发布到 AppStore 或 PlayStore 时,这非常有效。我需要再次更改架构并发布到 AppStore 或 PlayStore,并且我需要处理我的应用程序的新安装或更新,其中架构更改为以下

    class Bill extends Realm.Object {}
        Bill.schema = {
          name: 'Bill',
          primaryKey: 'id',
          properties: {
            id: { type: 'string', indexed: true },
            year: 'int',
            month: 'int',
            description: 'string',
            dateCreated: 'int',
            dateDeleted: 'int',
        }
    };

    class User extends Realm.Object {}
        User.schema = {
          name: 'User',
          primaryKey: 'id',
          properties: {
            id: 'string',
            name: 'string?',
            email: 'string?',
            photoUrl: 'string?',
          }
    };

通过在每个模式中再添加一个字段。

那么我应该如何配置我的领域架构版本呢?

我应该像下面这样配置:

const realm = new Realm([
              {schema: Bill, schemaVersion: 1}, 
              {schema: User, schemaVersion: 1}
            ]);

但这可能会因新安装而崩溃。

4

1 回答 1

-1

schemaVersion您应该为所有数据库设置全局,而不是为每个模型。并执行到当前版本的迁移,就像文档中描述的那样:

您可以通过更新 schemaVersion 并定义可选的迁移函数来定义迁移和关联的模式版本。您的迁移函数提供了将数据模型从以前的模式转换为新模式所需的任何逻辑。打开 Realm 时,仅当需要迁移时,才会应用迁移功能将 Realm 更新到给定的模式版本。

如果没有提供迁移功能,那么在更新到新的 schemaVersion 时,自动添加的任何新属性和旧属性都会从数据库中删除。如果您在升级版本时需要更新旧属性或填充新属性,您可以在迁移功能中执行此操作。例如,假设我们要迁移之前声明的 Person 模型。您可以使用旧的 firstName 和 lastName 属性填充新架构的 name 属性:

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;
});

迁移成功完成后,您的应用程序可以像往常一样访问 Realm 及其所有对象。

于 2018-06-07T14:47:35.957 回答