所以我正在使用 API 开发 PWA。我刚刚设法设置代码以从 API 获取国家/地区并将它们存储在我的 indexedDB 中。但是我不断收到“idb.js:23 Uncaught (in Promise) DOMException: 无法在‘IDBObjectStore’上执行‘put’:对象存储使用内联键并且提供了键参数。”我试图阅读有关它的内容,但对于这个异常的含义还不够清楚。这是我正在处理的代码:
fetch(apiURL)
.then(response => {
return response.json();
})
.then(data => {
dataBee.then(db => {
if (!db) return;
let txn = db.transaction('countryRecords', 'readwrite');
let countryStore = txn.objectStore('countryRecords');
//data is a multi-nested object from the API
for (let currency in data) {
for (let res in data[currency]) {
countryStore.put(
data[currency],
data[currency][res]["currencyId"]
);
}
}
return txn.complete;
})
.then(() => {
console.log("countries successfully added");
})
});
最佳答案
首先,这应该做什么?
for (let res in data[currency]) {
countryStore.put(
data[currency],
data[currency][res]["currencyId"]
);
}
因为目前它正在做的是“使用 N 个不同的主键将数据[货币]存储在我的数据库中 N 次”。这几乎肯定不是您想要做的。如果您希望能够根据存储在数组中的多个不同键在数据库中查找条目,请使用多条目索引。
该错误是因为当您的对象存储期望主键作为数据对象本身的属性出现时,您显式指定了主键(put
的第二个参数)。这就是向 createObjectStore
提供 keyPath
参数的作用。如果您的 keyPath 是“whatever”,那么它将在 data[currency].whatever
中查找以查找主键。
因此,您可以通过将代码更改为以下内容来消除错误消息:
for (let res in data[currency]) {
countryStore.put(
data[currency]
);
}
但这仍然几乎肯定不是您想要做的,因为它只会使用相同的主键将相同的数据写入数据库 N 次,导致数据库中只有一个对象并浪费大量时间反复写。如果数据库中的一个对象是您想要的结果,您可以这样做:
countryStore.put(data[currency]);
然后,如果您需要以不同的方式查询它,请使用索引。
关于javascript - 我在测试 PWA 时不断收到 IDBObjectStore 错误。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51174529/