let openRequest = indexedDB.open("myDatabase", 1);
openRequest.onupgradeneeded = function(e) {
let db = e.target.result;
// Create an object store named "books", with a key path of "isbn"
let store = db.createObjectStore("books", {keyPath: "isbn"});
// Create an index on the "author" property of the objects in the store
store.createIndex("author", "author", {unique: false});
};
openRequest.onsuccess = function(e) {
console.log("Success! Got a handle on the database.");
};
openRequest.onerror = function(e) {
console.error("Unable to open database: ", e.target.errorCode);
};?
// Step 1: Open or create a database
var request = indexedDB.open("myDatabase", 1);
// Step 2: Handle the database events
request.onerror = function(event) {
// Handle errors
console.log("Error opening database");
};
request.onsuccess = function(event) {
// Get reference to the opened database
var db = event.target.result;
console.log("Database opened successfully");
// Further database operations can be performed here
};
// Step 3: Define the database structure in case of upgrade
request.onupgradeneeded = function(event) {
// Get reference to the opened database
var db = event.target.result;
// Create an object store (table) to store data
var objectStore = db.createObjectStore("myObjectStore", { keyPath: "id" });
// Define indexes if needed
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
};?
Explanation :indexedDB.open()
method to open or create a database. It takes two parameters: the name of the database and the version number. If the database doesn't exist, it will be created. If it does exist, the version number will determine whether an upgrade is needed.get(), getAll(), getAllKeys(), openCursor()
, and openKeyCursor()
.var objectStore = db.createObjectStore("storeName", { keyPath: "id" });?
var objectStore = db.createObjectStore("storeName", { keyPath: ["lastName", "firstName"] });?
var objectStore = db.createObjectStore("storeName", { autoIncrement: true });?
indexedDB.open()
method. Here's how you can create an object store:// Step 1: Open or create a database
var request = indexedDB.open("myDatabase", 1);
// Step 2: Handle the database events
request.onerror = function(event) {
// Handle errors
console.log("Error opening database");
};
request.onsuccess = function(event) {
// Get reference to the opened database
var db = event.target.result;
console.log("Database opened successfully");
// Further database operations can be performed here
};
// Step 3: Define the database structure in case of upgrade
request.onupgradeneeded = function(event) {
// Get reference to the opened database
var db = event.target.result;
// Create an object store (table) to store data
var objectStore = db.createObjectStore("myObjectStore", { keyPath: "id" });
// Define indexes if needed
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
};?
myDatabase
", 1). The first parameter is the name of the database, and the second parameter is the version number. If the database doesn't exist, it will be created. If it does exist and the version number is greater than the existing version, the onupgradeneeded event will be triggered.myObjectStore
" with a key path of "id
". We also define two indexes named "name
" and "email
" on the "name
" and "email
" properties of the stored objects, respectively.myObjectStore
" will be created with the specified key path and indexes within the database. You can then use this object store to store and retrieve data within your IndexedDB database. // Step 1: Open or create a database
var request = indexedDB.open("myDatabase", 1);
// Step 2: Handle the database events
request.onerror = function(event) {
// Handle errors
console.log("Error opening database");
};
request.onsuccess = function(event) {
// Get reference to the opened database
var db = event.target.result;
console.log("Database opened successfully");
// Step 3: Start a transaction
var transaction = db.transaction(["myObjectStore"], "readwrite");
// Step 4: Get the object store
var objectStore = transaction.objectStore("myObjectStore");
// Step 5: Add data to the object store
var data = { id: 1, name: "John Doe", email: "john@example.com" };
var addRequest = objectStore.add(data);
// Step 6: Handle the result of the add operation
addRequest.onsuccess = function(event) {
console.log("Data added successfully");
};
addRequest.onerror = function(event) {
console.log("Error adding data");
};
};
// Step 7: Define the database structure in case of upgrade
request.onupgradeneeded = function(event) {
// Get reference to the opened database
var db = event.target.result;
// Create an object store if it doesn't exist
var objectStore = db.createObjectStore("myObjectStore", { keyPath: "id" });
// Define indexes if needed
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
};?
myDatabase
", 1).myObjectStore
".myObjectStore
").add()
method on the object store to add the data. The add()
method takes the data as a parameter.let openRequest = indexedDB.open("myDatabase", 1);
openRequest.onsuccess = function(e) {
let db = e.target.result;
let transaction = db.transaction("books", "readonly");
let objectStore = transaction.objectStore("books");
let request = objectStore.openCursor();
request.onsuccess = function(e) {
let cursor = e.target.result;
if (cursor) {
console.log("Key: ", cursor.key);
console.log("Value: ", cursor.value);
// Continue to the next item
cursor.continue();
} else {
console.log("End of data");
}
};
request.onerror = function(e) {
console.error("Error opening cursor: ", e.target.errorCode);
};
};
openRequest.onerror = function(e) {
console.error("Unable to open database: ", e.target.errorCode);
};?
authors
and books
. Each book
object has an authorId
field, which is the key of the author in the authors
object store.let db; // Assuming db is the opened IndexedDB database
// Get the transaction
let transaction = db.transaction(["books", "authors"]);
// Get the object stores
let bookStore = transaction.objectStore("books");
let authorStore = transaction.objectStore("authors");
// Let's find the details of the book and its author with bookId=1
let bookId = 1;
// Request to get the book
let bookRequest = bookStore.get(bookId);
bookRequest.onsuccess = function(e) {
let book = e.target.result;
console.log("Book: ", book.title);
// Request to get the author using the authorId from the book
let authorRequest = authorStore.get(book.authorId);
authorRequest.onsuccess = function(e) {
let author = e.target.result;
console.log("Author: ", author.name);
};
authorRequest.onerror = function(e) {
console.error("Error fetching author: ", e.target.error);
};
};
bookRequest.onerror = function(e) {
console.error("Error fetching book: ", e.target.error);
};?
books
" object store. Then, using the authorId
from the book, it fetches the author from the "authors
" object store. This simulates a join operation. authorRequest.onerror = function(e) {
console.error("Error fetching author: ", e.target.error);
};?
// Open the database
const dBOpenRequest = window.indexedDB.open("toDoList", 4);
dBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
console.log(`Upgrading to version ${db.version}`);
// 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 });
};?
// Asynchronous usage
var request = indexedDB.open("myDatabase", 1);
request.onerror = function(event) {
console.log("Error opening database");
};
request.onsuccess = function(event) {
var db = event.target.result;
console.log("Database opened successfully");
// Further database operations can be performed here
};?
async/await
with IndexedDB promises).var transaction = db.transaction(["objectStoreName"], "readwrite");?
var transaction = db.transaction(["objectStoreName"], "readonly");?
indexedDB.open(name, version);
let openRequest = indexedDB.open('store', 1);
openRequest.onupgradeneeded = function () {
// triggers if the client had no database
// ...perform initialization...
};
openRequest.onerror = function () {
console.error('Error', openRequest.error);
};
openRequest.onsuccess = function () {
let db = openRequest.result;
// continue working with database using db object
};?
deleteDatabase()
method of the IDBFactory interface requests the deletion of a database. The method returns an IDBOpenDBRequest
object immediately and performs the deletion operation asynchronously. let deleteRequest = indexedDB.deleteDatabase("myDatabase");
deleteRequest.onsuccess = function() {
console.log("Database deleted successfully");
};
deleteRequest.onerror = function(event) {
console.error("Error deleting database:", event.target.errorCode);
};?
let openRequest = indexedDB.open("store", 2);
openRequest.onupgradeneeded = ...;
openRequest.onerror = ...;
openRequest.onsuccess = function() {
let db = openRequest.result;
db.onversionchange = function() {
db.close();
console.log("Database is outdated, please reload the page.")
};
// ...the db is ready, use it...
};
openRequest.onblocked = function() {
// this event shouldn't trigger if we handle onversionchange correctly
// it means that there's another open connection to same database
// and it wasn't closed after db.onversionchange triggered for it
};?
tables
” or “collections
”, where the data is stored. A database may have multiple stores: one for users, another for goods, and more. Despite being named an “object-store” IndexedDB, primitives get stored too.let openRequest = indexedDB.open("myDatabase", 1);
openRequest.onupgradeneeded = function(e) {
let db = e.target.result;
// Create an object store named "books" with "isbn" as the key path
let store = db.createObjectStore("books", { keyPath: "isbn" });
};
openRequest.onsuccess = function(e) {
let db = e.target.result;
// Start a transaction on the "books" object store
let transaction = db.transaction("books", "readwrite");
let store = transaction.objectStore("books");
// Add a book to the object store
let book = { isbn: "9781234567890", title: "Sample Book" };
let request = store.add(book);
request.onsuccess = function() {
console.log("Book added successfully");
};
request.onerror = function(event) {
console.error("Error adding book:", event.target.errorCode);
};
// Commit the transaction
transaction.oncomplete = function() {
console.log("Transaction completed");
};
transaction.onerror = function(event) {
console.error("Transaction error:", event.target.errorCode);
};
// Close the database connection
db.close();
};
openRequest.onerror = function(e) {
console.error("Unable to open database:", e.target.errorCode);
};?
createObjectStore()
method of the IDBDatabase interface creates and returns a new object store or index. The method takes the store's name and a parameter object that lets you define optional properties. You can use the property to identify individual objects in the store uniquely. As the property is an identifier, it should be unique to every object, and every object should have that property. db.createObjectStore(name, options);
// Create an objectStore for this database
let objectStore = db.createObjectStore('toDoList', { keyPath: 'taskTitle' });?
let openRequest = indexedDB.open('db', 2);
// create/upgrade the database without version checks
openRequest.onupgradeneeded = function () {
let db = openRequest.result;
if (!db.objectStoreNames.contains('books')) {
// if there's no "books" store
db.createObjectStore('books', { keyPath: 'id' }); // create it
}
};?
IDBDatabase.transaction(storeNames, mode, options);
let transaction = db.transaction('books', 'readwrite'); // (1)
// get an object store to operate on it
let books = transaction.objectStore('books'); // (2)
let book = {
id: 'js',
price: 10,
created: new Date(),
};
let request = books.add(book); // (3)
request.onsuccess = function () {
// (4)
console.log('Book added to the store', request.result);
};
request.onerror = function () {
console.log('Error', request.error);
};?
put()
` and `add()
`. Both store key-value pairs, but behave differently on key conflict.put()
and add()
methods that store values. The put(value, [key])
adds values to the store. The object store supplies the key only if the object store does not have keyPath
or autoIncrement
option. If there is already a value with the same key, it gets replaced. The add(value, [key])
function is the same as the put method, except if a value with the same key already exists, the request fails, and an error with the name "ConstraintError
" gets created.let request = books.add(book);
delete
` method, which takes a key or key range as argument, or by calling `clear
` to remove all records from the store. The call format is similar to the getAll()
method. If we want to delete everything, we can use the clear method to clear the entire storage.// find the key where price = 5
let request = priceIndex.getKey(5);
request.onsuccess = function () {
let id = request.result;
let deleteRequest = books.delete(id);
};
books.clear(); // clear the storage.?
IDBKeyrange
object and call on the lowerbound and upperbound methods. lowerBound()
generates a new key range with only a lower bound. It is closed by default and includes the lower endpoint value. The upperBound()
function generates a new upper-bound key range, and it is closed by default and includes the upper endpoint value. The following methods include store get, getAll, getKey, getAllKeys
, or count to perform the actual search. They accept a query argument that can be either an exact key or a key range.// get one book
books.get('js');
// get books with 'css' <= id <= 'html'
books.getAll(IDBKeyRange.bound('css', 'html'));
// get books with id < 'html'
books.getAll(IDBKeyRange.upperBound('html', true));
// get all books
books.getAll();
// get all keys, where id > 'js'
books.getAllKeys(IDBKeyRange.lowerBound('js', true));?
index
”.let request = indexedDB.open("myDB");
request.onsuccess = function(e) {
let db = e.target.result;
let tx = db.transaction("ObjectStore");
let store = tx.objectStore("ObjectStore");
// Get operation
let getRequest = store.get(1);
getRequest.onsuccess = function() {
console.log("Get operation:", getRequest.result);
};
// Cursor operation
let cursorRequest = store.openCursor();
cursorRequest.onsuccess = function() {
let cursor = cursorRequest.result;
if (cursor) {
console.log("Cursor operation:", cursor.value);
cursor.continue();
}
};
};?
get
" operation retrieves the object with key 1, and the "cursor
" operation iterates over all the objects in the store. `onerror`/`onsuccess`
handlers for every request in IndexedDB. You can use a single set of handlers at the transaction level to handle success or error events for multiple requests within the transaction.request.onerror = function (event) {
if (request.error.name == 'ConstraintError') {
console.log('Book with such id already exists'); // handle the error
event.preventDefault(); // don't abort the transaction
event.stopPropagation(); // don't bubble error up, "chew" it
} else {
// do nothing
// transaction will be aborted
// we can take care of error in transaction.onabort
}
};?
setTimeout
. IndexedDB does not hold the transaction until these reach completion. This process is especially noticeable when using fetch and setTimeout
combined with an IndexedDB transaction. The IndexedDB spec's authors feel that transactions should be short-lived. Primarily for reasons of performance. lock
" the stores for writing. So, if one part of the program initiates readwrite on the books object store, another portion of the application that wishes to do the same must wait: the new transaction "hangs
" until the previous one reaches completion. If transactions take a long time, this might cause unusual delays.let request1 = books.add(book);
request1.onsuccess = function () {
fetch('/').then((response) => {
let request2 = books.add(anotherBook); // (*)
request2.onerror = function () {
console.log(request2.error.name); // TransactionInactiveError
};
});
};?