indexeddb

How to delete an Index in an existing IndexedDB


When I try to delete a IndexedDB Index in onupgradeneeded, I get one of 2 errors depending on whether I include the 1st statement below or not.

With the 1st statement, I get an exception saying "A version change transaction is running", indicating that I can't initiate a new transaction.

Without the 1st statement, I get "Cannot read properties of undefined (reading 'deleteIndex')", indicating I need the transaction.

So how can I delete the Index from the database? I'd like to do this in js, but would be ok to use Chrome's devtools as a backup. Thanks for any help you can provide.

 myStore = myDatabase.transaction('myStoreName',"readwrite").objectStore('myStoreName');
 myStore.deleteIndex('myIndex');


Solution

  • Do not start a new transaction. Instead, use the implicit version change transaction that is available to the upgradeneeded event handler.

    var request = indexedDB.open('mydb', 1234);
    request.addEventListener('upgradeneeded', event => {
      const db = event.target.result;
      if (db.objectStoreNames.contains('mystore')) {
        // Get a ref to the store in the current transaction
        const store = db.objectStore('mystore');
        if (store.indexNames.contains('myindex')) {
          // Delete the index during the current transaction
          console.log('deleting index', 'myindex');
          store.deleteIndex('myindex');
        } else {
          console.log('index %s not found so not deleting', 'myindex');
        }
      }
    });