4

I want to update one of the objecstores of my indexeddb database in the onupgradeneeded. I want to check, if this index exists in this objecstore, then there's no changes to be done. but if not i want to update it's index.

Al Ryan Acain
  • 477
  • 8
  • 17

1 Answers1

14
    var request = indexedDB.open(...);
    request.onupgradeneeded = function(event) {
      // Get the IDBDatabase connection
      var db = event.target.result;

      // This is the implied IDBTransaction instance available when
      // upgrading, it is type versionchange, and is similar to
      // readwrite.
      var tx = event.target.transaction;

      // Get the store from the transaction. This assumes of course that 
      // you know the store exists, otherwise use 
      // db.objectStoreNames.contains to check first.
      var store = tx.objectStore('myStore');

      // Now check if the index exists
      if(store.indexNames.contains('myIndex')) {
        // The store contains an index with that name
        console.log('The index myIndex exists on store myStore');

        // You can also access the index and ensure it has the right 
        // properties you want. If you want to change the properties you 
        // will need to delete the index then recreate it.
        var index = store.index('myIndex');
        
        // For example
        if(index.multiEntry) {
          console.log('myIndex is flagged as a multi-entry index');
        }

        if(index.unique) {
          console.log('myIndex is flagged with the unique constraint');
        }

      } else {
        // The store does not contain an index with that name
        console.log('The index myIndex does not exist on store myStore');

        // Can create it here if you want
        store.createIndex('myIndex', ...);
      }

    };
VnoitKumar
  • 1,350
  • 15
  • 29
Josh
  • 17,834
  • 7
  • 50
  • 68
  • Great answer, Thanks! – Al Ryan Acain Aug 12 '16 at 05:22
  • 1
    Where is the official (or unofficial) documentation for `contains`? I have searched through all possible sources (MDN, w3.org etc.) and [this question](http://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript), but I can't seem to find any mentioning of this native method. And where can I read about `contains`? – lyrically wicked Aug 17 '16 at 05:37
  • 2
    https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/indexNames and https://developer.mozilla.org/en-US/docs/Web/API/DOMStringList – Josh Aug 17 '16 at 11:48