gpt4 book ai didi

javascript - 在测试我的 PWA 时,我不断收到 IDBObjectStore 错误。

转载 作者:行者123 更新时间:2023-11-30 14:30:58 28 4
gpt4 key购买 nike

所以我正在开发一个使用 API 的 PWA。我刚刚设法设置代码以从 API 获取国家并将它们存储在我的 indexedDB 中。但是我不断收到“idb.js:23 Uncaught (in promise) DOMException: Failed to execute 'put' on 'IDBObjectStore': The object store uses in-line keys and the key parameter was provided.”我曾尝试阅读它,但对于此异常的含义还不够清楚。这是我正在处理的代码:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com