Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an indexeddb composite key

Tags:

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

like image 549
SnareChops Avatar asked Nov 22 '15 07:11

SnareChops


1 Answers

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

like image 133
SnareChops Avatar answered Oct 06 '22 02:10

SnareChops