IndexedDB IDBObjectStore.add 错误:“生成的键无法插入到值中”

Mat*_*att 5 javascript indexeddb

我试图向对象存储中添加一些值,但收到此错误(在第 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));
    };
  });
}
Run Code Online (Sandbox Code Playgroud)

以下是该活动的示例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
Run Code Online (Sandbox Code Playgroud)

chi*_*nce 1

我找到原因和解决方案

简而言之,该store.add值不是 object({}),因此object.id = autoGeneratedId会引发错误

就我而言,我使用

            database.createObjectStore(storeName, {
                keyPath: 'id',
                autoIncrement: true
            })
Run Code Online (Sandbox Code Playgroud)

并使用事务获取存储

            store2.add(1)
            store2.add(2)
Run Code Online (Sandbox Code Playgroud)

1.id = "val" 会引发错误

当我将其更改为时store2.add({k: "v"}),它修复了