所以我正在学习 IndexedDB,因为我必须在我公司正在规划的应用程序中使用它,而且我发现自己对光标和
IDBKeyRange
有点沮丧。事情,一切都很好,直到我尝试用IDBKeyRange.only
“过滤”。我有一个包含三个学生的“数据库”,其中两个将“科学”课程作为其数据的一部分。我有一个针对该领域(课程)的索引,当我创建一个光标来迭代学生时,它运行良好,直到我尝试过滤。我做错了什么IDBKeyRange
?这是我的代码。请注意,我添加了注释以帮助理解数据等。提前谢谢您:
/*
DATA AS A REFERNCE TO UNDERSTAND
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" });
*/
// this index exists
const courseIndex = store.index('course_index');
// Am I doing something wrong with this one?
const range = IDBKeyRange.only('Sciences');
// If I dont pass 'range', it works well
const courseIndexCursor = courseIndex.openCursor( range );
courseIndexCursor.onsuccess = event => {
const cursor = event.target.result; // this gets null if 'range' is used
if( cursor != null ){
console.log( cursor.value );
cursor.continue();
}
}
再次感谢您!
我能够找到问题所在,至少在这个问题上!事实证明,当我创建我的
course_index
时(在onupgradeneeded
期间),我是这样做的:
store.createIndex("course_index", ["course"], { unique: false });
所以我只需要改变这个:
const range = IDBKeyRange.only('Sciences');
对此(我将方括号添加到值中):
const range = IDBKeyRange.only(['Sciences']);
我的问题中发布的代码运行良好。万一有一天有人遇到同样的问题。我真的觉得我还缺少一些概念,但至少它现在正在工作。