Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an index to an existing object store in IndexedDB

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 });
  }
};
like image 768
Tal Ater Avatar asked Nov 02 '25 18:11

Tal Ater


1 Answers

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.

like image 55
Josh Avatar answered Nov 05 '25 09:11

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!