IDBObjectStore: put() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

注意:此功能在 Web Workers 中可用。

put() 方法是 IDBObjectStore 介面的一個方法,用於更新資料庫中指定記錄,或者在指定的項不存在時插入一條新記錄。

它會返回一個 IDBRequest 物件,並在單獨的執行緒中建立一個結構化克隆(structured clone)的 value,然後將其儲存到物件儲存中。這用於在事務模式為 readwrite 時新增新記錄或更新現有記錄。如果記錄儲存成功,則在返回的請求物件上會觸發一個 success 事件,其 result 屬性設定為儲存記錄的鍵,transaction 屬性設定為開啟此物件儲存的事務。

put 方法是更新或插入方法。有關僅插入的方法,請參閱 IDBObjectStore.add 方法。

請注意,如果您要更新的記錄擁有一個 IDBCursor,那麼使用 IDBCursor.update() 來更新它比使用 IDBObjectStore.put() 更可取。這樣做可以清楚地表明要更新的是現有記錄,而不是插入新記錄。

語法

js
put(item)
put(item, key)

引數

item

您希望更新(或插入)的項。

key 可選

您想更新的記錄的主鍵(例如,來自 IDBCursor.primaryKey)。

返回值

一個 IDBRequest 物件,後續與此操作相關的事件會在此物件上觸發。

如果操作成功,請求的 result 屬性的值將是新記錄或更新記錄的鍵。

異常

此方法可能會丟擲以下型別之一的DOMException

ReadOnlyError DOMException

如果與此操作關聯的事務處於只讀 模式,則會丟擲此異常。

TransactionInactiveError DOMException

如果此 IDBObjectStore 的事務不活躍,則會丟擲此異常。

DataError DOMException

如果滿足以下任一條件,則會丟擲此異常:

  • 該物件儲存使用內聯鍵或具有鍵生成器,並且提供了 key 引數。
  • 該物件儲存使用外部鍵且沒有鍵生成器,並且沒有提供 key 引數。
  • 該物件儲存使用內聯鍵但沒有 key 生成器,並且該物件儲存的鍵路徑未生成有效鍵。
  • 提供了 key 引數,但它不包含一個有效的鍵。
InvalidStateError DOMException

如果 IDBObjectStore 已被刪除或移除,則會丟擲此異常。

DataCloneError DOMException

如果正在儲存的資料無法透過內部結構化克隆演算法進行克隆,則會丟擲此異常。

示例

以下示例請求一個給定的記錄標題;當該請求成功時,onsuccess 函式會從 IDBObjectStore(透過 objectStoreTitleRequest.result 可獲得)獲取關聯的記錄,更新記錄的一個屬性,然後使用 put() 方法將更新後的記錄放回物件儲存。有關完整的可工作示例,請參閱我們的 To-do Notifications 應用(線上檢視示例)。

js
const title = "Walk dog";

// Open up a transaction as usual
const objectStore = db
  .transaction(["toDoList"], "readwrite")
  .objectStore("toDoList");

// Get the to-do list object that has this title as its title
const objectStoreTitleRequest = objectStore.get(title);

objectStoreTitleRequest.onsuccess = () => {
  // Grab the data object returned as the result
  const data = objectStoreTitleRequest.result;

  // Update the notified value in the object to "yes"
  data.notified = "yes";

  // Create another request that inserts the item back into the database
  const updateTitleRequest = objectStore.put(data);

  // Log the transaction that originated this request
  console.log(
    `The transaction that originated this request is ${updateTitleRequest.transaction}`,
  );

  // When this new request succeeds, run the displayData() function again to update the display
  updateTitleRequest.onsuccess = () => {
    displayData();
  };
};

規範

規範
Indexed Database API 3.0
# ref-for-dom-idbobjectstore-put①

瀏覽器相容性

另見