In indexedDB, how can I tell if a record has been updated or inserted using objectStore.put?

When using put () to insert data into a data store with indexeddb, is there a way to find out if this record has been inserted or updated?

I want to know if a record exists. Anyway, I'm going to insert / update data. This is hindered by the asynchronous api.

+4
source share
4 answers

Another template uses a cursor. You save a little CPU time.

req = objStore.openCursor(IDBKeyRange.lowerBound(key)) req.onsuccess = function(ev) { var cursor = ev.target.result; if (cursor) { // do update cursor.continue(next_key); } else { // do create } }; 

I discussed this issue at http://lists.w3.org/Archives/Public/public-webapps/2012OctDec/0481.html

+3
source

I do not think you can. You can try to add , which may result in a ConstraintError error. If you get this error, do put .

Or just get it first.

Running get + put always requires two queries. Running add + put is only possible one (add).

+1
source

You can update using the cursor :

 function insertOrUpdateSomething(db, obj) { var tx = db.transaction('storename','readwrite'); var store = tx.objectStore('storename'); store.openCursor(IDBKeyRange.only(obj.id)).onsuccess = function(event) { if(event.target.result) { console.log('Updating %s', JSON.stringify(obj)); event.target.result.update(obj); } else { console.log('Inserting %s', JSON.stringify(obj)); event.target.add(obj); } }; 
+1
source

You can use this function

 SaveOrUpdateDate (db,Table,By,Var,Value,CallbackSuccess, CallbackError){ var data = db.transaction([Table], "readwrite"); var object = data.objectStore(Table); var index = object.index('by_'+By); var request = index.get(String(Var)); request.onsuccess = function () { var result = request.result; if(typeof result !== 'undefined'){ result[Var] = Value; }else{ result = new Object(); result[By] = Var; result[Var] = Value; } var request2 = object.put(result); request2.onsuccess = function(e){ CallbackSuccess(); }; request2.onerror = function(e){ CallbackError(); }; } } 
0
source

Source: https://habr.com/ru/post/1481776/


All Articles