You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用IndexedDB索引删除数据报错:index.delete is not a function

问题解决:IndexedDB通过索引删除数据报错index.delete is not a function

问题原因

IndexedDB的索引对象(Index)本身没有delete方法,无法直接通过索引执行删除操作。必须先通过索引查询到目标记录的主键,再调用对象仓库(ObjectStore)的delete方法完成删除。

修正后的删除代码

var floorIndexValue = "2";
const request = window.indexedDB.open("AdminDatabase");

request.onsuccess = (event) => {
  const db = event.target.result;
  const txnRoom = db.transaction('rooms', 'readwrite');
  const storeRoom = txnRoom.objectStore('rooms');
  const index = storeRoom.index('floorIndex');

  // 通过索引打开游标,遍历所有匹配的记录
  const cursorRequest = index.openCursor([floorIndexValue]);

  cursorRequest.onerror = function(event) {
    console.log("游标查询错误: ", event);
  };

  cursorRequest.onsuccess = function(event) {
    const cursor = event.target.result;
    if (cursor) {
      // 通过主键删除当前记录
      storeRoom.delete(cursor.key);
      // 继续遍历下一条匹配记录
      cursor.continue();
    }
  };

  // 监听事务完成,确认所有删除操作执行完毕
  txnRoom.oncomplete = function() {
    console.log("所有匹配楼层的房间记录已删除");
    db.close();
  };

  txnRoom.onerror = function(event) {
    console.log("删除事务执行错误: ", event);
  };
};

额外说明

  1. 你创建索引时使用了数组格式['floorIndex'],因此查询游标时传入[floorIndexValue]的格式是正确的,能保证索引匹配逻辑生效。
  2. 必须监听事务的oncomplete事件,避免在删除操作未完成时就关闭数据库或执行后续逻辑,导致数据操作不完整。

内容的提问来源于stack exchange,提问作者Ozgur Baykal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 16:10:26