查询索引 IDB 上的对象
Query objects on index IDB
看起来应该很简单,但是我不知道如何根据某个索引查询对象存储。
数据库是这样创建的:
dbPromise = idb.open(idb_name, idb_version, db => {
const reviewStore = db.createObjectStore('reviews', {
keyPath: 'id'
});
reviewStore.createIndex('restaurant_id', 'restaurant_id', {unique: false});
});
我创建了 reviews
对象存储,其索引位于 restaurant_id
。
存储的数据如下所示:
{
comment: "Mission Chinese Food has grown...",
createdAt: 1504095567183,
id: 1123
restaurant_id: 1
}
但是,当我这样调用 get
时:
db.transaction('reviews').objectStore('reviews').get('1')...
我得到 id
为 1 或什么都没有的对象,而不是 restaurant_id
。
如何检索与指定索引值匹配的对象数组?
这可能会起作用:
db.transaction('reviews').objectStore('reviews').index('restaurant_id').getAll(1)
与您尝试的不同之处:
- 你必须明确地告诉它使用什么索引,否则它会查询主键,正如你所注意到的
get
检索单个记录,但 getAll
检索与查询匹配的所有记录的数组。旧浏览器(以及当前版本的Edge)不支持getAll
,但如果您需要a polyfill。
1
而不是 '1'
,可能只是您问题中的错字 :)
看起来应该很简单,但是我不知道如何根据某个索引查询对象存储。
数据库是这样创建的:
dbPromise = idb.open(idb_name, idb_version, db => {
const reviewStore = db.createObjectStore('reviews', {
keyPath: 'id'
});
reviewStore.createIndex('restaurant_id', 'restaurant_id', {unique: false});
});
我创建了 reviews
对象存储,其索引位于 restaurant_id
。
存储的数据如下所示:
{
comment: "Mission Chinese Food has grown...",
createdAt: 1504095567183,
id: 1123
restaurant_id: 1
}
但是,当我这样调用 get
时:
db.transaction('reviews').objectStore('reviews').get('1')...
我得到 id
为 1 或什么都没有的对象,而不是 restaurant_id
。
如何检索与指定索引值匹配的对象数组?
这可能会起作用:
db.transaction('reviews').objectStore('reviews').index('restaurant_id').getAll(1)
与您尝试的不同之处:
- 你必须明确地告诉它使用什么索引,否则它会查询主键,正如你所注意到的
get
检索单个记录,但getAll
检索与查询匹配的所有记录的数组。旧浏览器(以及当前版本的Edge)不支持getAll
,但如果您需要a polyfill。1
而不是'1'
,可能只是您问题中的错字 :)