gpt4 book ai didi

javascript - IndexedDB IDBObjectStore.add 错误 : "a generated key could not be inserted into the value"

转载 作者:行者123 更新时间:2023-12-03 06:59:46 32 4
gpt4 key购买 nike

我正在尝试将一些值添加到对象存储中,得到这个错误作为返回(在第 22 行)。对象存储使用 keyPath 'id' 和 autoincrement: true。

function cacheObject(storeName, object) {
return new Promise(function(resolve, reject) {
let transaction = db.transaction([storeName], "readwrite");

transaction.oncomplete = function(event) {
console.log("Transaction complete");
resolve(object);
};

transaction.onabort = function(event) {
console.log("Transaction aborted: " + event);
reject();
};

transaction.onerror = function (event) {
console.log("Transaction error: "+ event.toString());
reject();
};

let objectStore = transaction.objectStore(storeName);

let objectReq = objectStore.add(object);
objectReq.onsuccess = function (event) {
console.log("saved object to idb: " + JSON.stringify(object));
};
});
}

这是来自 onupgradeneeded 的样本事件:

  req.onupgradeneeded = function (e) {
let db = e.target.result;
console.log("Running idb onupgradeneeded");
if (!db.objectStoreNames.contains(STORY_STORE_NAME)) {
let storyStore = db.createObjectStore(STORY_STORE_NAME, {keyPath: "id", autoIncrement: true});
storyStore.createIndex('picture', 'picture', {unique: false});
storyStore.createIndex('text', 'text', {unique: false});
//more indexes created here

最佳答案

我找到了原因和解决方案
总之,store.add值不是对象({}),所以 object.id = autoGeneratedId会引发错误
就我而言,我使用

            database.createObjectStore(storeName, {
keyPath: 'id',
autoIncrement: true
})
并使用交易获取商店
            store2.add(1)
store2.add(2)
1.id = "val"会引发错误
当我把它改成 store2.add({k: "v"}) ,它修复

关于javascript - IndexedDB IDBObjectStore.add 错误 : "a generated key could not be inserted into the value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56244300/

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