Reputation: 1189
How do I add an index to a previously created object store, within the upgrade needed event?
Doing this on a new object store is well documented:
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("my-store",
{ keyPath: "id" }
);
objectStore.createIndex("idx_name", "index_this", { unique: false });
};
But how can I add an index to an object store that I previously created?
request.onupgradeneeded = function(event) {
var db = event.target.result;
if (!db.objectStoreNames.contains("my-store")) {
var objectStore = db.createObjectStore("my-store",
{ keyPath: "id" }
);
}
var myStore = ?????????????;
if (!myStore.indexNames.contains("idx_name")) {
myStore.createIndex("idx_name", "index_this", { unique: false });
}
};
Upvotes: 4
Views: 1195
Reputation: 18690
You want to retrieve a reference to the object store from the transaction that is implicitly provided to you from within the scope of the onupgradeneeded function.
function onupgradeneeded(event) {
var request = event.target;
var tx = request.transaction;
var store = tx.objectStore('store-name');
store.createIndex(...);
}
Keep in mind that you will have to rewrite your onupgradeneeded function so that you only attempt to get the store if it has been created, and that you only attempt to create the index if it has not yet been created. There are a couple of ways of doing that. One is to use the version number. You can test against the old version that existed before the upgrade, or the new/current version. E.g. use event.oldVersion
if you want. Alternatively, you can test if the store exists and separately test if the index exists, by looking up the store name using db.objectStoreNames.contains
, and looking up the index name in store.indexNames.contains
.
Upvotes: 8