I spent hours and hours searching for this one, and just by trial and error was I able to finally find the solution. Logging this in Stack Overflow for future searchers.
Q:
How do I create a composite key in indexeddb?
Keys are created in indexeddb on object stores using the following:
var db; var openRequest = indexedDB.open('myDB', 1); openRequest.addEventListener('error', () => { console.error('Unable to open db'); }); openRequest.addEventListener('upgradeneeded', function(event){ var store = db.createObjectStore('myStore', {keyPath: /* composite key */ } ); }); openRequest.addEventListener('success', function(){ db = openRequest.result; });
I have tried placing objects, defining multiple times, how does one create a composite key, or is this a limitation of the API?
Note: If you are looking for how to query a composite key using a range, please check out this post
A:
As it turns out, the answer is very simple, but not documented well anywhere I have looked, and not obvious at first glance. Use an array of strings...
var store = db.createObjectStore('myStore', {keyPath: ['id1', 'id2']} );
Composite indexes can also be created in the same fashion.
For work with composite key data, see the answer below by Malvineous
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With