4

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 });
  }
};

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Works great, thank you! Here is the code I ended up with: gist.github.com/TalAter/45e0b87ee0cf8b65f943c4320b092b0e

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.