Sample of IndexedDB with Autogenerating Keys

This post is more than 2 years old.

I'm still struggling my way through learning IndexedDB. I'm going to post examples as I learn - but as a warning - please consider anything I post as potentially wrong, misleading, and dangerous to the fabric of the universe.

In today's post - I simply wanted to create an objectstore (again, think of a table) with an autogenerating key. The (mostly) incredibly useful MDN documentation talks a bit about how you can either provide a key manually or use a key generator. However it doesn't explain how you actually use a key generator. This seems to imply that indexeddb has a way to allow you to write your own logic to create keys. For example, perhaps by combining a few properties, or perhaps by simply counting the existing objects and adding one to it. I'm still not sure if that actually exists. However, there is a simpler way of doing it.

When you create your object store, you provide a name and a map of options. One option is the keypath, which is basically the property of your data expected to hold a value. The second option is a key called autoIncrement. This defaults to false, but if you set it to true, you get nicely autoincrementing keys. Here's an example by itself:

And here is a complete template. Note it also supports a simple button to add data and then dump it to console. Note that adding data currently barfs on Chrome with:

Uncaught Error: DATA_ERR: DOM IDBDatabase Exception 5

Which according to the MDN reference is "Data provided to an operation does not meet requirements." If I had to guess, I'd say maybe Chrome isn't supporting the auto generated key. (Note - I just did a test and confirmed this. Well, I'll be focusing then on Firefox, which seems to be more to spec.) For a complete example, see the code below.

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by Ido posted on 9/23/2012 at 1:25 PM

Thanks for this example.
Btw, on Chrome (both 21 and 23) it's not working. I saw it's throw:
NotFoundError: DOM IDBDatabase Exception 8

Comment 2 by Raymond Camden posted on 9/23/2012 at 5:44 PM

Chrome still doesn't support onupgradeneeded, which is the spec. :(

http://www.raymondcamden.co...

Comment 3 by Raymond Camden posted on 9/23/2012 at 5:49 PM

FYI, Chrome Canary supports it.

Comment 4 by Ido Green posted on 9/23/2012 at 11:29 PM

Yep... btw, I did this short example (forked from your example) that works both in FF and Chrome ;)

Comment 5 by Raymond Camden posted on 9/24/2012 at 12:06 AM

Good to hear. :)