Updating an Existing IndexedDB objectStore
A few weeks ago I have published an article in the CodeProject website called “Getting Started with IndexedDB”. One of the questions that I got was how to update an existing objectStore with a new index. This post will answer the question.
The updateneeded Event
In IndexedDB the only way to update the database is through the updateneeded event. That event is raised when you use the IndexedDB open function with a database version number which is greater than the current database version number. For example, lets assume that there is an IndexedDB database with the name PeopleDB which has a version number of 1. The following code will raise the updateneeded event:
The open function returns
IDBRequest object (since all the functionality in IndexedDB is asynchronous by default) which you will use to wire handlers for onsuccess, onerror and onupgradeneeded. You will wire the events like in the following example:
The example shows how to wire the event handlers for the success, error and upgradeneeded events. The db is a variable that will hold the database after it is opened.
Creating a New Index
In the event handler for the updateneeded event you can create a new objectStore index. Here is an example of how to do that:
In the example you use the event parameter that is passed to the updateneeded handler to get the opened update transaction. Through the transaction you can get the relevant objectStore which will be manipulated. On the objectStore you use the createIndex function to create a new index. The rest of the code is inserting a new person into the objectStore.
Updating an IndexedDB existing objectStore is done using the updateneeded which is raised when you change the database version.