2

Trying to update a records name field but instead of updating the record it creates a new record.

My Code

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');
    };
}

}

Looking for record 5 and attempting to change it's name field to John. I have been following Raymond Camden tutorial http://code.tutsplus.com/tutorials/working-with-indexeddb-part-2--net-35355 and searched for other examples like IndexedDB update by id but can't seem to adapt them to work for what I need.

Community
  • 1
  • 1
csb
  • 326
  • 6
  • 15
  • Can you share how you defined the objectstore? – Raymond Camden Oct 03 '14 at 11:00
  • Hi Raymond just figured this out. I needed to place the id of the record into the objRequest. var objRequest = store.put(data, +r); r is the key number. Just like to say I thought your tutorial was very helpfully just got a little lost with the delete and updating functions. – csb Oct 03 '14 at 11:10
  • Interesting. The docs for put (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore.put) say specifying the PK is optional. In my tests I've left it out becuz my object contains the PK. Wonder why yours didn't? – Raymond Camden Oct 03 '14 at 11:19
  • possible duplicate of [Indexeddb adds a new value instead of updating an existing value](http://stackoverflow.com/questions/25130117/indexeddb-adds-a-new-value-instead-of-updating-an-existing-value) – Josh Oct 03 '14 at 12:17

1 Answers1

2

Thanks to Tiffany Brown's article which can be found at https://dev.opera.com/articles/introduction-to-indexeddb/ I found a solution which was to add the key within the put call.

var objRequest = store.put(data, +r);

Josh explains in his answer Indexeddb adds a new value instead of updating an existing value that it might have something to do with keys being in-line or out-of-line depending on weather the object store has a key path or not.

Community
  • 1
  • 1
csb
  • 326
  • 6
  • 15