Delete multiple records in IndexedDB based on index

I use IndexedDB, and I have two repositories of objects: equip (represents other equipment, the primary key is tagNo) and equipParts (represents parts of the equipment and has an index that is based on the tag number / serial number, the primary key is seqNo, with the tagNo field, which represents equipment, part of which is part).

If I delete an entry in the equipment, I want to delete all entries in equipParts with the NoO equip tag (just like equipParts.tagNo = equip.tagNo).

Excerpt from my code:

var tx = db.transaction(["equip", "equipParts"],"readwrite"); var estore = tx.objectStore("equip"); var pstore = tx.objectStore("equipParts"); var tagIndex = pstore.index("by_tagNo"); var pdestroy = tagIndex.openCursor(IDBKeyRange.only(tagno)); //opens all records bearing the selected tag number pdestroy.onsuccess = function() { var cursor = pdestroy.result; if (cursor) { if (cursor.value.tagNo == tagno) { pstore.delete(cursor.value.seqNo); //I guess I'm wrong here } cursor.continue; } } pdestroy.onerror = function() { alert("Deletion attempt NG"); } var ereq = estore.delete(tagno); ereq.onsuccess = function(e) { alert("Form deletion OK"); window.location = "index.html"; } ereq.onerror = function(e) { alert("Form deletion NG"); window.location = "index.html"; } db.close(); 

The problem is that only the record in the hardware is deleted; records in equipParts are stored there. Is there a way to delete multiple entries in the IndexedDB object store based on a non-unique index (which may be the main key of the parent object store)?

+13
indexing cursor indexeddb
source share
2 answers

You must get the primary keys to delete entries.

 var pdestroy = tagIndex.openKeyCursor(IDBKeyRange.only(tagno)); pdestroy.onsuccess = function() { var cursor = pdestroy.result; if (cursor) { pstore.delete(cursor.primaryKey); cursor.continue; } } 

Alternative but ineffective

 var pdestroy = tagIndex.openCursor(IDBKeyRange.only(tagno)); pdestroy.onsuccess = function() { var cursor = pdestroy.result; if (cursor) { cursor.delete(); cursor.continue; } } 
+14
source share

I found the easiest approach with this

 index.iterateCursor(IDBKeyRange, (cursor) => { if(cursor){ cursor.delete(); cursor.continue(); } }); 

that way, if you have an asynchronous function, you can just use

 await index.iterateCursor... 

and wait for the promise from the other side

0
source share

All Articles