Lesson 2: Working with IndexedDB CHAPTER 16 593
The createIndex method is called during a database migration, within the onupgrad-
eneeded event handler, to ensure that the index is created when the version is updated.
Removing indexes
If you decide that an index is no longer needed, you can remove it by creating a database
migration that uses the object store’s deleteIndex() method, as shown in the following
example code.
var openRequest = indexedDB.open('Library', 3);
openRequest.onupgradeneeded = function(response) {
var store = response.currentTarget.transaction.objectStore("authors");
store.deleteIndex('lastName');
};
Removing object stores
As you probably guessed, the steps to remove an object store are very similar to the steps
for creating one. You create a new migration that uses the database’s deleteObjectStore()
method as follows.
var openRequest = indexedDB.open('Library', 4);
openRequest.onupgradeneeded = function(response) {
response.currentTarget.result.deleteObjectStore("authors");
};
Using transactions
When your object stores are in place, you must use the IDBTransaction object to add or
remove objects. An IDBTransaction object, which is a transaction, is created by using the
transaction method of the database object and takes the following parameters.
■■objectStoreNames pecifies the object stores with which the transaction will work. If S
only one object store is needed, the parameter can be a single string. If multiple object
stores are needed, pass an array of strings. The following is an example of opening a
transaction for a single object store.
var trans = db.transaction('authors');
Here is an example of opening a transaction for multiple object stores.
var trans = db.transaction(['authors', 'books']);
■■mode Optional when possible values are readonly and readwrite. If not specified, the
transaction will be defaulted to readonly. If left in readonly mode, multiple transactions
can be run concurrently. The following is an example of a transaction being opened in
readonly mode.