我向架构添加了一个新属性。该属性是新的主键。 (在现实生活中,该主键对应于记录键和用户键的组合键。)
我的代码有效。但是,感觉很复杂(必须将结果转换为数组,然后将其克隆):
function migrationThatWorks(oldRealm, newRealm) {
let results = readRecords(newRealm);
let cloned = clone(_.values(results));
newRealm.delete(results);
cloned.forEach(r => r.Key = 'test' + r.Id);
cloned.forEach(r => newRealm.create(mySchema, r, true));
readRecords(newRealm);
}
function clone(c) {
return JSON.parse(JSON.stringify(c));
}
有更好的方法吗?
理想情况下,我想要类似的东西:
realm.updateAll(mySchema, r => r.Key = 'test' + r.Id);
这是一个完整的工作示例:
var Realm = require('realm');
var _ = require('lodash');
var mySchema = 'MySchema';
v1();
v2();
function v1() {
var schema1 = {
name: mySchema,
primaryKey: 'Id',
properties: {
Id: 'int',
}
};
var realm1 = new Realm({
schema: [
schema1
],
schemaVersion: 1
});
createRecord(realm1, 1);
createRecord(realm1, 2);
readRecords(realm1);
realm1.close();
}
function v2() {
var schema2 = {
name: mySchema,
primaryKey: 'Key',
properties: {
Id: 'int',
Key: 'string',
}
};
let realm2 = new Realm({
schema: [
schema2
],
schemaVersion: 2,
migration: migrationThatWorks,
});
}
function migrationThatWorks(oldRealm, newRealm) {
let results = newRealm.objects(mySchema);
let cloned = clone(_.values(results));
newRealm.delete(results);
cloned.forEach(r => r.Key = 'test' + r.Id);
cloned.forEach(r => newRealm.create(mySchema, r, true));
readRecords(newRealm);
}
function clone(c) {
return JSON.parse(JSON.stringify(c));
}
function readRecords(realm) {
var result = realm.objects(mySchema);
console.log(result);
if (_.values(result).length !== 2) {
throw 'not expecting this';
}
return result;
}
function createRecord(realm, id) {
realm.write(() => {
realm.create(mySchema, {
Id: id,
}, true);
});
}