IDBDatabase: createObjectStore() 方法
注意:此功能在 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:
ConstraintErrorDOMException-
如果数据库中已存在具有给定名称(基于区分大小写的比较)的对象 store,则抛出此异常。
InvalidAccessErrorDOMException-
如果
autoIncrement设置为 true 且keyPath为空字符串或数组,则抛出此异常。 InvalidStateErrorDOMException-
如果该方法不是从
versionchange事务回调中调用的,则抛出此异常。 SyntaxError-
如果
keyPath选项包含无效的键路径,则抛出此异常。 TransactionInactiveErrorDOMException-
如果请求是在不存在的源数据库上进行的(例如,数据库已被删除或移除),或者关联的升级事务已完成或正在处理请求,则抛出此异常。
示例
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① |
浏览器兼容性
加载中…
另见
- 使用 IndexedDB
- 开始事务:
IDBDatabase - 使用事务:
IDBTransaction - 设置键的范围:
IDBKeyRange - 检索和修改数据:
IDBObjectStore - 使用游标:
IDBCursor - 参考示例:待办事项通知(查看实时示例)。