如何创建indexeddb组合键

iklwldmw  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(2)|浏览(208)

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

2cmtqfgy

2cmtqfgy1#

答:

事实证明,答案很简单,但是我看过的任何地方都没有很好的文档记录,乍一看也不明显。

var store = db.createObjectStore('myStore', 
    {keyPath: ['id1', 'id2']}
);

也可以用相同的方式创建复合索引。
对于使用组合键数据,see the answer below by Malvineous

xxhby3vn

xxhby3vn2#

再补充一点,实际上使用复合键,也不是很清楚。
添加一个对象并不太糟糕:

myStore.add({
    id1: 'a',  // first part of key
    id2: 'b',  // second part of key
    etc: 'c',  // other data to store
});

然而,使用组合键再次获取对象并不是那么容易,需要传递一个数组作为键,其值的顺序与最初传递给createObjectStore()keyPath数组的顺序相同。

myStore.get(['a', 'b'])   // look for id1=a + id2=b

这里,数组中的第一个值(a)与keyPath[0]匹配,在上面的答案中,keyPath[0]被设置为id1

相关问题