so I am learning IndexedDB because I have to use it in a app my company is planing, and I am finding myself a bit frustrated with cursors and IDBKeyRange. The thing, everything works great until I try to 'filter' with IDBKeyRange.only. I have a 'database' with three students, two of them have the 'Sciences' course as part of their data. I have an index working towards that field (course) and when I create a cursor to iterate over the students, it works well UNTIL I try to filter. What am I doing wrong with IDBKeyRange? This is my code. Note that I placed comments to help understanding the data, etc. Thank you in advanced:
/*
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();
}
}
Thank you again!
I was able to find the problem, at least with this one! It turns out that, when I created my
course_index(duringonupgradeneeded), I did it like this:store.createIndex("course_index", ["course"], { unique: false });So I only had to change this:
const range = IDBKeyRange.only('Sciences');to this (I added the square brackets to the value):
const range = IDBKeyRange.only(['Sciences']);And the code posted in my question worked perfectly. In case anyone has the same problem someday. I really thing I am missing some concepts yet, but at least it is working now.