How do I update data in indexedDB?

39,053

Solution 1

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".

Solution 2

A bit late for an answer, but possible it helps others. I still stumbled -as i guess- over the same problem, but it's very simple:

If you want to INSERT or UPDATE records you use objectStore.put(object) (help)
If you only want to INSERT records you use objectStore.add(object) (help)

So if you use add(object), and a record key still exists in DB, it will not overwritten and fires error 0 "ConstraintError: Key already exists in the object store".

If you use put(object), it will be overwritten.

Solution 3

I'm a couple of years late, but thought it'd be nice to add my two cents in.

First, check out BakedGoods if you don't want to deal with the complex IndexedDB API.

It's a library which establishes a uniform interface that can be used to conduct storage operations in all native, and some non-native client storage facilities. It also maintains the flexibility and options afforded to the user by each. Oh, and it's maintained by yours truly :) .

With it, placing one or more data items in an object store can be as simple as:

bakedGoods.set({
    data: [{key: "key1", value: "value1"}, {key: "key2", value: "value2"}),
    storageTypes: ["indexedDB"],
    complete: function(byStorageTypeResultDataObj, byStorageTypeErrorObj){}
});

Now to answer the actual question...

Lets begin by aggregating the valuable information spread across the existing answers:

  • IDBObjectStore.put() adds a new record to the store, or updates an existing one

  • IDBObjectStore.add() adds a new record to the store

  • IDBCursor.update() updates the record at the current position of the cursor

As one can see, OP is using an appropriate method to update a record. There are, however, several things in his/her code, unrelated to the method, that are incorrect (with respect to the API today at least). I've identified and corrected them below:

var cursorRequest = objectStore.openCursor(keyRange); //Correctly define result as request

cursorRequest.onsuccess = function(e){                //Correctly set onsuccess for request
    var objCursor = cursorRequest.result;             //Get cursor from request
    var obj = objCursor.value;                        //Get value from existing cursor ref
    console.log(obj);
    var request = objCursor.update(obj);             
    request.onsuccess = function(){
        callback();
    }
    request.onerror = function(e){
        console.log("DBM.activitati.edit -> error " + e); //Use "console" to log :)
    }

}   
cursorRequest.onerror = function(e){                  //Correctly set onerror for request
    console.log("DBM.activitati.edit -> error " + e); //Use "console" to log :)
}      

Solution 4

this is case of update infos of an user object

var transaction = db.transaction(["tab_user"], "readwrite");
var store = transaction.objectStore("tab_user");

var req = store.openCursor();
req.onerror = function(event) {
  console.log("case if have an error");
};

req.onsuccess = function(event) {
    var cursor = event.target.result;
    if(cursor){
        if(cursor.value.idUser == users.idUser){//we find by id an user we want to update
            var user = {};
            user.idUser = users.idUser ;
            user.nom = users.nom ;

            var res = cursor.update(user);
            res.onsuccess = function(e){
                console.log("update success!!");
            }
            res.onerror = function(e){
                console.log("update failed!!");
            }
        }
        cursor.continue();
    }
    else{
        console.log("fin mise a jour");
    }
}
Share:
39,053
Michael
Author by

Michael

Updated on July 10, 2020

Comments

  • Michael
    Michael almost 4 years

    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!

  • Michael
    Michael almost 12 years
    Thank you! This indexedDB looks increasingly better! I thought it doesn't know to handle this so easy..
  • buley
    buley almost 12 years
    IDB is amazing. Ask away if you run into problems but also search SO for answers on stuff. I try not to let any question go unanswered.
  • Velojet
    Velojet about 8 years
    Thanks for drawing attention to cursor.update(). MDN: "Returns an IDBRequest object, and, in a separate thread, updates the value at the current position of the cursor in the object store. This can be used to update specific records."
  • Miron
    Miron about 7 years
    Clear to understand and easy to implement, +1
  • code
    code over 5 years
    @buley How can I append a value to an array field in IDB?