问题描述
我有一个对象存储区,其键路径为"id"(自动递增),并且在该存储区上具有从服务器生成的键路径为"myId"的唯一索引.当我需要更新记录时,我将没有可用的"id",因此考虑到索引是唯一的,如何仅通过使用"myId"来更新记录?
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?
我已经尝试使用mystore.put(record),但是由于存在具有"myId"的记录,因此出现了错误.
I already tried using mystore.put(record), but that gives an error since a record with "myId" already exists.
推荐答案
由于您在myId
属性上已经具有唯一的键索引,因此可以基于该值检索记录.您需要使用 only
IDBKeyRange
和cursor
查询,如下所示:
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
}
};
此外,如果要使用同一事务进行更新,则需要像我一样将其设置为readwrite
而不是readonly
.
Also, if you want to update using the same transaction you'll need to make it a readwrite
not readonly
as I did.
这篇关于Indexeddb-通过索引键更新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!