IndexedDB更新记录
问题描述:
尝试更新记录名称字段,但不更新记录,而是创建新记录。IndexedDB更新记录
我的代码
function editName(e) {
var transaction = db.transaction(["people"],"readwrite");
var store = transaction.objectStore("people");
var request = store.get(5);
request.onsuccess = function(e) {
var data = e.target.result;
data.name = "John";
var objRequest = store.put(data);
objRequest.onsuccess = function(e){
console.log('Success in updating record');
};
}
}
寻找记录5和试图改变它的名字领域的约翰。我一直在关注Raymond Camden教程http://code.tutsplus.com/tutorials/working-with-indexeddb-part-2--net-35355并搜索其他示例,如IndexedDB update by id,但似乎无法使其适应我需要的工作。
答
感谢蒂芙尼布朗的文章,其中可以找到https://dev.opera.com/articles/introduction-to-indexeddb/我发现了一个解决方案,这是在放呼吁添加密钥。
var objRequest = store.put(data, +r);
乔希解释了他的答案Indexeddb adds a new value instead of updating an existing value,它可能有一些做的钥匙在线或乱行取决于天气的对象存储有关键路径或不是。
你可以分享你如何定义对象库吗? – 2014-10-03 11:00:41
嗨雷蒙德刚刚发现了这一点。我需要将记录的id放入objRequest中。 var objRequest = store.put(data,+ r); r是关键数字。就像说我认为你的教程非常有用,只是因为删除和更新功能而迷失了方向。 – csb 2014-10-03 11:10:52
有趣。 Put的文档(https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore.put)表示指定PK是可选的。在我的测试中,我把它留给了我,因为我的对象包含了PK。想知道你为什么没有? – 2014-10-03 11:19:05