1

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.

ebi
  • 4,862
  • 6
  • 29
  • 40

1 Answers1

6

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.

Vadim
  • 8,701
  • 4
  • 43
  • 50
Aaron Powell
  • 24,927
  • 18
  • 98
  • 150
  • Thanks, this seems like exactly what I need. Follow-up question - I need to update many records in one transaction, would the method shown here be the best way - http://stackoverflow.com/a/13666741/1781631 – ebi May 13 '13 at 05:25
  • If you have to update many records in one transaction then you might want to just walk the cursor using cursor.continue(nextMyId) instead of using a keyRange that specifies just one object. – dgrogan May 13 '13 at 16:00
  • @dgrogan - Can you provide an example of that? I do need to update many records at once. – ebi May 21 '13 at 02:07