Taming IndexedDB [3/3]

Dani Vijay
Mar 8, 2018 · 3 min read

It’s time to become that ultimate IndexedDB Ninja everyone dreams to be! But it is impossible without reading Taming IndexedDB [1/3] and Taming IndexedDB [2/3]. If you covered that already, it’t time to the finale!!

Working with Indexes

If you are reading this series from the beginning, you may recall the term ‘Index’.

Index is a kinda object store for organizing data for another object store. For example, if you’re storing users, you may want to fetch them later by their name or favorite movies.

Indexes kicks in if we want only a subset of the data based on a particular property. It is possible to create an index of any property, and then fetch data according to it rather than depending on primary keys.

Range is defined using IDBKeyRange object, which can be set using upperBound, lowerBound or simply bound(with both of the previous bounds as parameters). This may sound little confusing, so lets look at the syntax.

# lower bound
IDBKeyRange.lowerBound(indexKey);
# upperbound
IDBKeyRange.upperBound(indexKey);
# combination of the above two
IDBKeyRange.bound(lowerIndexKey, upperIndexKey);

It’ time to check out a demo, in which, an index on the “price” property in the “store” object store is created. A small form with two inputs deals with the upper and lower limits of the range. Imagine passing in the lower and upper bounds to the function as floating point numbers representing prices.

function searchItems(lower, upper) {
if (lower === '' && upper === '') {return;}
var range;
if (lower !== '' && upper !== '') {
range = IDBKeyRange.bound(lower, upper);
} else if (lower === '') {
range = IDBKeyRange.upperBound(upper);
} else {
range = IDBKeyRange.lowerBound(lower);
}
dbPromise.then(function(db) {
var tx = db.transaction(['store'], 'readonly');
var store = tx.objectStore('store');
var index = store.index('price');
return index.openCursor(range);
}).then(function showRange(cursor) {
if (!cursor) {return;}
console.log('Cursored at:', cursor.key);
for (var field in cursor.value) {
console.log(cursor.value[field]);
}
return cursor.continue().then(showRange);
}).then(function() {
console.log('Done cursoring');
});
}

Conditions are used to check the presence and apply the bounds and cursor is used to iterate through obtained objects.

Versioning the Database

It’s about to wind up, but there is an important concept that should be addressed before dealing with IndexedDB databases. While using idb.open, we should specify a database version as a second parameter. If this version number is greater than the version of the existing database, the upgrade callback executes, allowing us to add object stores and indexes to the database.

The oldVersion property of upgradeDb is used to detect the existing database version in database. Then it can be used to perform operations accordingly. A switch is utilized for the same, generally.

var dbPromise = idb.open('test-db7', 2, function(upgradeDb) {
switch (upgradeDb.oldVersion) {
case 0:
upgradeDb.createObjectStore('store', {keyPath: 'name'});
case 1:
var peopleStore = upgradeDb.transaction.objectStore('store');
peopleStore.createIndex('price', 'price');
}
});

Here, the db version is set as 2. Then different operations are performed in the case of version 0 and 1, by checking current version using upgradeDb.OldVersion.

If you make it this far, hats off to you! You’ve gained enough knowledge on indexedDB to get going. It’s time to impress that guy or girl with your newly gained skills with IDB… Hmm.. Well, probably that might be a bad idea. Anyway, see you later, alligator!!

Beginner's Guide to Mobile Web Development

Tutorials to guide beginners to perform various tasks in…

Dani Vijay

Written by

Full Stack Web Dev | Tech Evangelist | https://twitter.com/UtmostDev | https://github.com/danivijay/ | https://linkedin.com/in/danivijay

Beginner's Guide to Mobile Web Development

Tutorials to guide beginners to perform various tasks in the field of Mobile Web Development.

Dani Vijay

Written by

Full Stack Web Dev | Tech Evangelist | https://twitter.com/UtmostDev | https://github.com/danivijay/ | https://linkedin.com/in/danivijay

Beginner's Guide to Mobile Web Development

Tutorials to guide beginners to perform various tasks in the field of Mobile Web Development.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store