ebi
ebi

Reputation: 4902

Indexeddb - Update record by index key

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.

Upvotes: 1

Views: 7160

Answers (1)

Aaron Powell
Aaron Powell

Reputation: 25099

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.onsuccess = 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.

Upvotes: 6

Related Questions