I have a problem with filtering using indexedDB.
I have users with name aaa, bbb, ccc and index is on name.
Here's my code and no matter which IDBKeyRange filter I apply on cursor, I get empty list. I tried with bound and lowerBound.
const usersData = [
{ id: '1', name: 'bbb', email: 'bbb@somewhere.com' },
{ id: '2', name: 'aaa', email: 'aaa@somewhere.com' },
{ id: '3', name: 'ccc', email: 'ccc@somewhere.com' },
];
let db;
let request = window.indexedDB.open('test1', 1);
request.onerror = function(e) {
console.error(e);
};
request.onsuccess = function(e) {
db = e.target.result;
console.log('success, db: ', db);
};
request.onupgradeneeded = function(e) {
db = e.target.result;
let objectStore = db.createObjectStore('user', { keyPath: 'id' });
for (let user of usersData) {
objectStore.add(user);
}
objectStore.createIndex('name', 'name');
}
function readAll() {
let objectStore = db.transaction(['user'])
.objectStore('user');
let range = null;
//range = IDBKeyRange.lowerBound('aaa', true); // ? doesn't working
range = IDBKeyRange.bound(['aaa'], ['ccc'], true, true);
objectStore.openCursor(range).onsuccess = function(e) {
let cursor = e.target.result;
if (cursor) {
console.log(cursor.key, cursor.value);
cursor.continue();
}
else {
console.log('---------------------------------');
}
};
}
Change the code so that you open the cursor on the index, not the object store.
// ...
let index = objectStore.index('name');
// ...
index.openCursor(range).onsuccess = // ...
// ...