首页 > 解决方案 > 如何在已经存在的 indexedDB 中的已经存在的 objectStore 中“放置”新值?

问题描述

我把自己绑在了结中,试图更新 in 中的一系列四个objectStore条目indexedDB

这就是我想要实现的(在伪代码中):

let myDatabase = indexedDB('myDatabase', 1);
let myObjectStore = myDatabase.myObjectStore;
myObjectStore.entry1 = 'newValue1';
myObjectStore.entry2 = 'newValue2';
myObjectStore.entry3 = 'newValue3';
myObjectStore.entry4 = 'newValue4';

但是,当然,这不是那么简单的事情。

我知道我需要使用put. 但是,尽管尝试了许多方法,但我无法走得更远。

在第一次创建时,我已经成功地设置和填充了:objectStoreindexedDB

// SET UP VALUES OBJECT

let valuesObject = {

  entry1 : 'a',
  entry2 : 'b',
  entry3 : 'c',
  entry4 : 'd'
};


// SET UP INDEXED DATABASE

const setUpIndexedDatabase = (valuesObject) => {

  let database
  const databaseVersion = 1; 
  const databaseName = \'myDatabase\';
  const databaseOpenRequest = indexedDB.open(databaseName, databaseVersion);

  databaseOpenRequest.onupgradeneeded = () => {

    database = databaseOpenRequest.result;

    let myObjectStore = database.createObjectStore('myObjectStore');

    myObjectStore.transaction.oncomplete = () => {

      let objectStoreValues = database.transaction('Values', 'readwrite').objectStore('Values');

      const valuesEntries = Object.entries(valuesObject);

      for (let i = 0; i < valuesEntries.length; i++) {

        objectStoreValues.add(valuesEntries[i][1], valuesEntries[i][0]);
      }
    }
  }


  databaseOpenRequest.onsuccess = () => {

    database = databaseOpenRequest.result;

    // >>> THIS IS THE BIT THAT I NEED TO WRITE <<<

    database.close();
  }
}

setUpIndexedDatabase(valuesObject);

到目前为止,一切都很好。onupgradeneeded如果尚不存在数据库,则上面的代码会触发该事件,这会创建myObjectStore并使用四个键值对填充它。

但是,如果数据库确实存在并且已经包含myObjectStore,那么我使用的每个代码变体都put无法更新键的值并返回各种错误——而且通常根本没有错误。

我要做的就是更新数据库中的值。

put我认为问题是当数据库版本保持不变并且onupgradeneeded不触发时,我不知道如何正确使用。

标签: javascriptecmascript-6indexeddb

解决方案


如果要更新数据库中已经存在的值,可以使用以下代码进行操作(例如,我正在更新entry1条目):

databaseOpenRequest.onsuccess = function(event) {
    db = event.target.result;

    const objectStore = db.transaction('myObjectStore', 'readwrite').objectStore('myObjectStore');
    const request = objectStore.put('e', 'entry1');
    request.onerror = function(event) {
        // There was an error while updating.
    };
    request.onsuccess = function(event) {
        // The update was successful.
    };
}

推荐阅读