The IDBObjectStore
interface of the IndexedDB API represents an object store in a database. Records within an object store are sorted according to their keys. This sorting enables fast insertion, look-up, and ordered retrieval.
This example shows a variety of different uses of object stores, from updating the data structure with IDBObjectStore.createIndex
inside an onupgradeneeded
function, to adding a new item to our object store with IDBObjectStore.add
. For a full working example, see our To-do Notifications app (view example live).
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Database initialized.";
db = DBOpenRequest.result;
};
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Error loading database.";
};
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
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.";
};
const newItem = [
{
taskTitle: "Walk dog",
hours: 19,
minutes: 30,
day: 24,
month: "December",
year: 2013,
notified: "no",
},
];
const transaction = db.transaction(["toDoList"], "readwrite");
transaction.oncomplete = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction completed.";
};
transaction.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction not opened due to error. Duplicate items not allowed.";
};
const objectStore = transaction.objectStore("toDoList");
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Request successful.";
};