Twitter: raymondcamden

Address: Lafayette, LA, USA

Sample of IndexedDB with Autogenerating Keys

04-26-2012 8,530 views Development, JavaScript, HTML5 5 Comments

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.

Related Blog Entries


These comments will soon be imported into Disqus. To add a comment, use Disqus above.
  • Commented on 09-23-2012 at 4:25 AM
    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
  • Commented on 09-23-2012 at 8:44 AM
    Chrome still doesn't support onupgradeneeded, which is the spec. :(
  • Commented on 09-23-2012 at 8:49 AM
    FYI, Chrome Canary supports it.
  • Commented on 09-23-2012 at 2:29 PM
    Yep... btw, I did this short example (forked from your example) that works both in FF and Chrome ;)
  • Commented on 09-23-2012 at 3:06 PM
    Good to hear. :)