使用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); }; };
额外说明
- 你创建索引时使用了数组格式
['floorIndex'],因此查询游标时传入[floorIndexValue]的格式是正确的,能保证索引匹配逻辑生效。 - 必须监听事务的
oncomplete事件,避免在删除操作未完成时就关闭数据库或执行后续逻辑,导致数据操作不完整。
内容的提问来源于stack exchange,提问作者Ozgur Baykal
相关产品推荐
相关产品推荐

