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.

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.

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.

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…

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.