原Schema:
const JoinedDataSchema = {
name: 'JoinedData',
primaryKey: 'cid',
properties: {
cid:'string',
uid:'string',
clubName:'string',
clubIcon:'string',
owner:'string',
ownerId:'string',
isLike:'int',
desc:'string',
roomId:'string',
joinTime:'double',
}
};
新Schema:
const JoinedDataSchema = {
name: 'JoinedData',
primaryKey: 'cid',
properties: {
cid:'string',
uid:'string',
clubName:'string',
clubIcon:'string',
owner:'string',
ownerId:'string',
isLike:'int',
desc:'string',
roomId:'string',
joinTime:'double',
clubMemberCount:'int',
notice:'string',
tags:'string[]',
}
};
打开Realm:
Realm.open({
schemaVersion: 1, ///因为之前没加过schemaVersion 所以默认为0
schema: realmUntils.ClubJoinedAllSchema,
path: this.props.loginData.userId + realmUntils.ClubJoinedPath,
migration: (oldRealm, newRealm) => {
if (oldRealm.schemaVersion < 1) {
const oldObjects = oldRealm.objects('JoinedData');
const newObjects = newRealm.objects('JoinedData');
//新增字段在这里
newObjects.clubMemberCount = 0;
newObjects.notice = '';
newObjects.tags = [];
//修改字段如下
// 遍历所有对象,然后设置新架构中的 `name` 属性
for (var i = 0; i < oldObjects.length; i++) {
newObjects[i].name = oldObjects[i].firstName + ' ' + oldObjects[i].lastName;
}
//name替换firstName和lastName
}
}
}).then(
例:
Realm.open({
schemaVersion: 2,
path: this.props.loginData.userId + realmUntils.ClubJoinedPath,
schema: realmUntils.ClubJoinedAllSchema,
migration: (oldRealm, newRealm) => {
if (oldRealm.schemaVersion < 1) {
const oldObjects = oldRealm.objects('JoinedData');
const newObjects = newRealm.objects('JoinedData');
newObjects.clubMemberCount = 0;
newObjects.notice = '';
newObjects.tagsList = [];
for (var i = 0; i < oldObjects.length; i++) {
newObjects[i].name = oldObjects[i].clubName;
newObjects[i].icon = oldObjects[i].clubIcon;
}
} else if (oldRealm.schemaVersion < 2) {
const oldObjects = oldRealm.objects('JoinedData');
const newObjects = newRealm.objects('JoinedData');
for (var i = 0; i < oldObjects.length; i++) {
newObjects[i].name = oldObjects[i].clubName;
newObjects[i].icon = oldObjects[i].clubIcon;
newObjects[i].tagsList = oldObjects[i].tags;
}
}
}
}).then(realm => {
let ClubJoined = realm.objects('ClubJoined').filtered(`userId = "${this.props.loginData.userId}"`)[0];
realm.write(() => {
let joinedData = [];
clubQueryMineState.result.map((item, index) => {
item.cid ? joinedData.push(item) : null;
});
ClubJoined.joinedData = joinedData;
});
this.setState({
refreshState: RefreshState.Idle,
dataSource: clubQueryMineState.result,
shouldQuery: true
})
});
网友评论