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
2条答案
按热度按时间2cmtqfgy1#
答:
事实证明,答案很简单,但是我看过的任何地方都没有很好的文档记录,乍一看也不明显。
也可以用相同的方式创建复合索引。
对于使用组合键数据,see the answer below by Malvineous
xxhby3vn2#
再补充一点,实际上使用复合键,也不是很清楚。
添加一个对象并不太糟糕:
然而,使用组合键再次获取对象并不是那么容易,需要传递一个数组作为键,其值的顺序与最初传递给
createObjectStore()
的keyPath
数组的顺序相同。这里,数组中的第一个值(
a
)与keyPath[0]
匹配,在上面的答案中,keyPath[0]
被设置为id1
。