在React Native中,你应该把迁移代码或删除领域数据库的代码(忽略迁移)放在哪里,并且只运行一次?
每次返回登录屏幕时,我都尝试删除领域数据库。当我尝试登录时,它应该将用户信息保存到 Realm 中,然后应用程序正常进行。然而事实并非如此,似乎因为Realm数据库被删除了,所以它没有地方可以保存它。我本以为一旦我登录,通过将用户信息保存到 Realm 中,它会初始化 Realm,然后将用户保存在 Realm 中。
在调试模式下,似乎即使删除了 Realm 数据库,一切都正常。调试模式要慢很多,那么是否存在某个时间问题?
有没有初始化Realm的方法?
这就是我为使迁移正常工作所做的事情。
我有
realm.js
位于 /src
中,我保存所有反应文件。当我需要使用我的领域时我import realm from 'path/to/realm.js';
在 realm.js
中,我有旧模式和新模式。
import Realm from 'realm';
const schema = {
name: 'mySchema',
properties: {
name: 'string',
}
};
const schemaV1 = {
name: 'mySchema',
properties: {
name: 'string',
otherName: 'string',
}
};
注意他们有相同的名字。然后在我的
realm.js
的底部,我曾经有export default new Realm({schema: [schema]});
我现在有这个:
export default new Realm({
schema: [schemaV1],
schemaVersion: 1,
migration: (oldRealm, newRealm) => {
// only apply this change if upgrading to schemaVersion 1
if (oldRealm.schemaVersion < 1) {
const oldObjects = oldRealm.objects('schema');
const newObjects = newRealm.objects('schema');
// loop through all objects and set the name property in the new schema
for (let i = 0; i < oldObjects.length; i++) {
newObjects[i].otherName = 'otherName';
}
}
},
});
如果您不需要迁移数据,您只需使用新架构版本和新架构打开 Realm,它也应该可以工作。
如果您刚刚添加或删除了架构的字段,则可以执行空迁移。这是我的realm.js 文件:
import Realm from 'realm';
//models
import Registros from '../models/registros';
import Local from '../models/local';
export default function getRealm() {
return Realm.open({
schema: [Registros, Local],
schemaVersion: 1, //add a version number
migration: (oldRealm, newRealm) => {
},
});
}
只需将 schemaVersion={2} 添加到 RealmProvider