Indexeddb - Update record by index key

女生的网名这么多〃 提交于 2019-12-12 01:03:09

问题


I have an object store with keypath "id" (autoincrement), and a unique index on that store with keypath "myId" that is generated from a server. When I need to update a record, I won't have "id" available, so how can I update the record just by using "myId" considering that the index is unique?

I already tried using mystore.put(record), but that gives an error since a record with "myId" already exists.


回答1:


Since you've already got a unique key index on your myId property you can retrieve the record based on that value. You'll need to use the only IDBKeyRange and a cursor query, like so:

var transaction = db.transaction('myStore');
var store = transaction.objectStore('myStore');
var index = store.index('myId_Index');
var keyRange = IDBKeyRange.only(obj.myId);

var request = index.openCursor(keyRange);

request.onsucess = function (e) {
    var cursor = e.target.result;

    if (cursor) {
        var item = cursor.value;
        obj.id = item.id;
        //save the object
    }
};

Also, if you want to update using the same transaction you'll need to make it a readwrite not readonly as I did.



来源:https://stackoverflow.com/questions/16478227/indexeddb-update-record-by-index-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!