CloudKit JS 提供了保存、删除和获取记录的方法,但没有简单的方法来更新现有记录。 documentation解释如何去做:
var query = {
operationType : 'forceUpdate',
recordType: 'List',
record : {
recordName : 'TheRecordIWannaUpdate',
fields: { TheFieldToUpdate: { 'value': 42}}
}
};
container.publicCloudDatabase.performQuery(query).then(function(response) {
if(response.hasErrors) {
console.log(response.errors[0]);
} else {
console.log('It's working')
}
});
我尝试了这段代码,它返回了It's working
但是我的记录没有更新,这段代码有什么问题?
最佳答案
如文档所述,update
是在大多数情况下使用的正确操作类型。
update | Update an existing record. Only the fields you specify are changed.
在您阅读记录和尝试应用新更新之间,其他客户端总是有可能更新记录。 recordChangeTag
是服务器知道您阅读的版本的方式,这就是文档说明您需要在更新操作中发送它的原因。
If operationType is update, set the recordChangeTag key to the value of the existing record [in the record dictionary].
当您尝试更新已被其他人更新的记录时,您将从服务器收到冲突,因为您的 recordChangeTag 是旧的,您应该以您的应用程序中有意义的任何方式处理该冲突。也许您想告诉用户,也许您只想合并更改。
在特殊情况下,您可能希望强制更新成功。在这种情况下,您可以使用 forceUpdate
operationType,告诉服务器忽略冲突并进行此更新,在这种情况下您不必包含 recordChangeTag
。
forceUpdate | Update an existing record regardless of conflicts. Creates a record if it doesn’t exist.
如果您使用正常的 update
operationType 并且收到成功(不是冲突),那么记录肯定会在服务器上更新。如果不是,则说明发生了其他事情。
值得一提的是,您可能会发现使用 RecordsBatchBuilder 更方便将更改发送到服务器时。以下是您可以使用它执行的操作的示例:
myDatabase.newRecordsBatchBuilder()
.createOrUpdate(record1)
.create(record2)
.update(record3)
.forceUpdate(record4)
.delete(record5)
.commit()
如您所见,它为您处理了很多选项。
关于javascript - 使用 CloudKit JS 更新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32143526/