首页 文章

Realm会对本机模式版本进行反应

提问于
浏览
-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}
            ]);

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

1 回答

  • -1

    您应该为所有数据库设置全局 schemaVersion ,而不是为每个模型设置 . 并执行到当前版本的迁移,如_1521710中所述:

    您可以通过更新schemaVersion并定义可选的迁移功能来定义迁移和关联的模式版本 . 您的迁移功能提供将数据模型从先前模式转换为新模式所需的任何逻辑 . 打开Realm时,仅当需要迁移时,才会应用迁移功能将Realm更新为给定的架构版本 . 如果未提供迁移功能,则在更新到新的schemaVersion时,将从数据库中删除自动添加的所有新属性和旧属性 . 如果在升级版本时需要更新旧属性或填充新属性,可以在迁移功能中执行此操作 . 例如,假设我们要迁移先前声明的Person模型 . 您可以使用旧的firstName和lastName属性填充新架构的name属性:Realm.open({
    schema:[PersonSchema],
    schemaVersion:1,
    迁移:(oldRealm,newRealm)=> {
    //仅在升级到schemaVersion 1时才应用此更改
    if(oldRealm.schemaVersion <1){
    const oldObjects = oldRealm.objects('Person');
    const newObjects = newRealm.objects('Person');

    //遍历所有对象并在新架构中设置name属性
    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及其所有对象 .

相关问题