How do I update data in indexedDB?

Michael picture Michael · Jun 27, 2012 · Viewed 33.1k times · Source

I have tried to get some information from W3C regarding the update of an objectStore item in a indexedDB database, but with not so much susccess. I found here a way to do it, but it doesn't really work for me.

My implementation is something like this

DBM.activitati.edit = function(id, obj, callback){
    var transaction = DBM.db.transaction(["activitati"], IDBTransaction.READ_WRITE);
    var objectStore = transaction.objectStore("activitati");
    var keyRange = IDBKeyRange.only(id);

    objCursor = objectStore.openCursor(keyRange);
    objCursor.onsuccess = function(e){
        var cursor = e.target.result;
        console.log(obj);
        var request = cursor.update(obj);
        request.onsuccess = function(){
            callback();
        }
        request.onerror = function(e){
            conosole.log("DBM.activitati.edit -> error " + e);
        }

    }   
    objCursor.onerror = function(e){
        conosole.log("DBM.activitati.edit -> error " + e);
    }                   
}

I have all DBM.activitati.(add | remove | getAll | getById | getByIndex) methods working, but I can not resolve this.

If you know how I can manage it, please, do tell!

Thank you!

Answer

buley picture buley · Jun 27, 2012

Check out this jsfiddle for some examples on how to update IDB records. I worked on that with another StackOverflower -- it's a pretty decent standalone example of IndexedDB that uses indexes and does updates.

The method you seem to be looking for is put, which will either insert or update a record if there are unique indexes. In that example fiddle, it's used like this:

    phodaDB.indexedDB.addUser = function(userObject){
        //console.log('adding entry: '+entryTxt);
        var db = phodaDB.indexedDB.db;
        var trans = db.transaction(["userData"],IDBTransaction.READ_WRITE);
        var store = trans.objectStore("userData");
        var request = store.put(userObject);

        request.onsuccess = function(e){
            phodaDB.indexedDB.getAllEntries();
        };
        request.onerror = function(e){
            console.log('Error adding: '+e);
        };
    };

For what it's worth, you've got some possible syntax errors, misspelling "console" in console.log as "conosole".