基于索引删除IndexedDB中的多个记录

use*_*708 13 indexing cursor indexeddb

我使用的是IndexedDB,我有两个对象存储:equip(代表不同的设备,主键tagNo)和equipParts(代表一个设备的部分,并且有一个基于标签号/序列号的索引,主键seqNo,带有字段tagNo,表示该部分所属的设备).

如果我删除一条记录装备,我想删除所有记录equipParts轴承TAGNO装备(就像"里equipParts.tagNo = equip.tagNo").

摘自我的代码:

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();
Run Code Online (Sandbox Code Playgroud)

问题是只删除装备中的记录; equipParts中的记录留在那里.有没有办法根据非唯一索引(可以是父对象库的主键)删除IndexedDB对象库中的多个记录?

Kya*_*Tun 14

您必须获取主键才能删除记录.

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

或者,但效率不高

var pdestroy = tagIndex.openCursor(IDBKeyRange.only(tagno)); 
pdestroy.onsuccess = function() {
  var cursor = pdestroy.result;
  if (cursor) {
      cursor.delete();
      cursor.continue;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 在光标打开时删除记录在 Safari 上是有问题的。即使有额外的匹配记录,游标也会变为空。获取所有主键,然后对每个主键调用`IDBObjectStore.delete()` 更可靠。 (3认同)
  • `openCursor` 返回 `IDBCursorWithValue`,需要读取记录值,而第一个返回没有记录值的 `IDBCursor`。 (2认同)