How do I update data in indexedDB?

后端 未结 4 953
情书的邮戳
情书的邮戳 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条回答
  • 2021-02-07 21:25

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

    0 讨论(0)
  • 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 :)
    }      
    
    0 讨论(0)
  • 2021-02-07 21:47

    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.

    0 讨论(0)
  • 2021-02-07 21:48

    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");
        }
    }
    
    0 讨论(0)
提交回复
热议问题