How do I update data in indexedDB?

后端 未结 4 960
情书的邮戳
情书的邮戳 2021-02-07 20:48

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, bu

4条回答
  •  旧时难觅i
    2021-02-07 21:32

    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 :)
    }      
    

提交回复
热议问题