使用IDBKeyRange.only创建游标返回null的问题求助
排查IDBKeyRange.only('Sciences')返回null的问题
以下是几个可能导致你遇到问题的原因及排查方向:
1. 索引创建参数错误
确保创建course_index时,键路径正确指向course字段,且未设置unique: true选项:
// 正确的索引创建方式 store.createIndex('course_index', 'course'); // 错误示例:如果设置了unique: true,重复的'Sciences'会导致索引中只保留一条数据 // store.createIndex('course_index', 'course', { unique: true });
如果索引设置了unique: true,第二条course: "Sciences"的数据插入时会失败,索引中只会存在第一条数据,最终导致查询无结果。
2. 数据与查询值的大小写/拼写不匹配
检查数据库中实际存储的course字段值,是否和你查询的'Sciences'完全一致(包括大小写、空格、拼写)。可以在不传入范围参数时,打印每条数据的course值确认:
courseIndex.openCursor().onsuccess = event => { const cursor = event.target.result; if (cursor) { console.log('实际course值:', cursor.value.course); // 检查是否为精确的'Sciences' cursor.continue(); } };
如果实际存储的是sciences(小写开头)或其他变体,IDBKeyRange.only('Sciences')自然匹配不到数据。
3. 事务模式或时机问题
- 确保查询操作所在的事务是
readonly或readwrite模式(查询用readonly足够),且事务未提前关闭。 - 如果插入数据和查询操作在同一个事务中,需确保插入操作完成后再执行查询(IndexedDB事务是异步的,需等待
put的onsuccess触发后再打开游标)。
4. 索引可用性验证
直接打印索引的键路径,确认索引确实关联到course字段:
console.log('索引键路径:', courseIndex.keyPath); // 应输出"course" console.log('索引是否存在:', store.indexNames.contains('course_index')); // 应输出true
修正后的示例代码
假设索引创建正确,以下是确保能查询到数据的完整流程:
// 打开数据库 const request = indexedDB.open('StudentDB', 1); request.onupgradeneeded = event => { const db = event.target.result; const store = db.createObjectStore('students', { keyPath: 'id' }); // 创建正确的索引 store.createIndex('course_index', 'course'); // 插入测试数据 store.put({ id: 1, name: "John Smith", gender: "Male", age: 21, course: "Sciences" }); store.put({ id: 2, name: "Theresa Martin", gender: "Female", age: 20, course: "Arts" }); store.put({ id: 3, name: "David Brown", gender: "Male", age: 20, course: "Sciences" }); }; request.onsuccess = event => { const db = event.target.result; // 开启readonly事务查询数据 const transaction = db.transaction('students', 'readonly'); const store = transaction.objectStore('students'); const courseIndex = store.index('course_index'); const range = IDBKeyRange.only('Sciences'); const cursorRequest = courseIndex.openCursor(range); cursorRequest.onsuccess = event => { const cursor = event.target.result; if (cursor) { console.log(cursor.value); cursor.continue(); } }; };
内容的提问来源于stack exchange,提问作者Alan Espinet
相关产品推荐
相关产品推荐

