IndexedDB索引查找失败求助:指定索引未找到
解决IndexedDB索引未找到的问题
问题原因
出现Uncaught DOMException: Failed to execute 'index' on 'IDBObjectStore': The specified index was not found.错误,核心原因是数据库的onupgradeneeded事件未触发,导致你编写的索引创建代码根本没执行。常见触发场景:
- 此前已创建过版本号为1的
Workouts数据库,修改索引逻辑后未升级版本号,浏览器直接复用旧数据库,不会执行新的Schema创建逻辑。 - 浏览器缓存了旧数据库实例,其中不存在你定义的
name_Type和specifics索引。
解决方案
1. 升级数据库版本号
将indexedDB.open("Workouts", 1)中的版本号从1改为更大的数值(比如2),浏览器会检测到版本变更,自动触发onupgradeneeded事件,执行索引创建代码:
// 升级版本号到2 const request = indexedDB.open("Workouts", 2);
2. 清除旧数据库(可选)
若升级版本号后问题仍存在,说明旧数据库残留,可临时添加代码删除旧数据库,刷新页面后再移除这段代码:
// 临时添加,执行一次后删除 window.indexedDB.deleteDatabase("Workouts"); window.location.reload();
修正后的完整代码示例
//Credit @alexeagleson - github // This works on all devices/browsers, and uses IndexedDBShim as a final fallback const indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB; // Open (or create) the database with upgraded version const request = indexedDB.open("Workouts", 2); request.onerror = function (event) { console.error("An error occurred with IndexedDB"); console.error(event); }; // Create the schema on create and version upgrade request.onupgradeneeded = function () { const db = request.result; // 先检查对象仓库是否存在,避免重复创建报错 if (!db.objectStoreNames.contains("workouts")) { const store = db.createObjectStore("workouts", { keyPath: "id" }); store.createIndex("name_Type", ["Type"], { unique: false }); store.createIndex("specifics", ["Type","Where","For"], {unique: false,}); } }; request.onsuccess = function () { console.log("Database opened successfully"); const db = request.result; const transaction = db.transaction("workouts", "readwrite"); const store = transaction.objectStore("workouts"); try { const nameIndex = store.index("name_Type"); const specificsIndex = store.index("specifics"); console.log("Indexes accessed successfully"); } catch (e) { console.error("Failed to access indexes:", e); } };
额外注意事项
- 每次修改数据库Schema(创建/删除对象仓库、索引),必须升级版本号,否则
onupgradeneeded事件不会触发。 - 数据库操作完成后,建议监听
transaction.oncomplete事件,确保事务提交后再进行后续操作。
内容的提问来源于stack exchange,提问作者potsandpans
相关产品推荐
相关产品推荐

