IDBDatabase: createObjectStore() 方法

Baseline 已廣泛支援

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

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

IDBDatabase 介面的 createObjectStore() 方法建立並返回一個新的 IDBObjectStore

該方法接受 store 的名稱以及一個引數物件,該物件允許你定義重要的可選屬性。你可以使用該屬性來唯一標識 store 中的各個物件。由於該屬性是一個識別符號,因此它應該對每個物件都是唯一的,並且每個物件都應該具有該屬性。

此方法只能versionchange 事務中呼叫。

語法

js
createObjectStore(name)
createObjectStore(name, options)

引數

name

要建立的新物件 store 的名稱。請注意,可以建立名稱為空的物件 store。

options 可選

一個選項物件,其屬性是該方法的可選引數。它包含以下屬性:

keyPath 可選

將由新物件 store 使用的 鍵路徑。如果為空或未指定,則物件 store 將在沒有鍵路徑的情況下建立,並使用 行外部索引鍵。你也可以將陣列傳遞給 keyPath

autoIncrement 可選

如果為 true,則物件 store 具有 鍵生成器。預設為 false

返回值

一個新的 IDBObjectStore

異常

此方法可能會引發一個 name 為以下型別之一的 DOMException

ConstraintError DOMException

如果資料庫中已存在具有給定名稱(基於區分大小寫的比較)的物件 store,則丟擲此異常。

InvalidAccessError DOMException

如果 autoIncrement 設定為 true 且 keyPath 為空字串或陣列,則丟擲此異常。

InvalidStateError DOMException

如果該方法不是從 versionchange 事務回撥中呼叫的,則丟擲此異常。

SyntaxError

如果 keyPath 選項包含無效的鍵路徑,則丟擲此異常。

TransactionInactiveError DOMException

如果請求是在不存在的源資料庫上進行的(例如,資料庫已被刪除或移除),或者關聯的升級事務已完成或正在處理請求,則丟擲此異常。

示例

js
// Let us open our database
const request = window.indexedDB.open("toDoList", 4);

// This handler is called when a new version of the database
// is created, either when one has not been created before
// or when a new version number is submitted by calling
// window.indexedDB.open().
// This handler is only supported in recent browsers.
request.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      "Error loading database.";
  };

  // Create an objectStore for this database

  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain

  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });

  objectStore.createIndex("notified", "notified", { unique: false });

  note.appendChild(document.createElement("li")).textContent =
    "Object store created.";
};

規範

規範
Indexed Database API 3.0
# ref-for-dom-idbdatabase-createobjectstore①

瀏覽器相容性

另見