-1

I know this questions has been asked several times . But I have not been able to find out the solution after getting error multiple times . this is the code of my indexed db

    request.onupgradeneeded = function(event) {
      var db = event.target.result;
   var upgradeTransaction = event.target.transaction;        
   var objectStore = db.createObjectStore("todostore", {keyPath: "timestamp"});     

UserFunction();     

     };

     function UserFunction(){
var ObjectStore = db.transaction("todostore").objectStore("todostore");
var index = ObjectStore.createIndex("ixName", "fieldName");
  }



Failed to execute 'createIndex' on 'IDBObjectStore': The database is not running a version change transaction.

I am calling this function of button click I want to add index with value when a button is clicked

<button onclick="UserFunction()">createIndex</button>
tayyab vohra
  • 83
  • 1
  • 2
  • 12

2 Answers2

0

You can only change the schema of the database during a version upgrade. Something like this is plausible:

function OnClick() {
  // assumes db is a previously opened connection
  var oldVersion = db.version; 
  db.close();

  // force an upgrade to a higher version
  var open = indexedDB.open(db.name, oldVersion + 1);
  open.onupgradeneeded = function() {
    var tx = open.transaction;
    // grab a reference to the existing object store
    var objectStore = tx.objectStore('todostore');
    // create the index
    var index = objectStore.createIndex('ixName', 'fieldName');
  };
  open.onsuccess = function() {
    // store the new connection for future use
    db = open.result;
  };
}
Joshua Bell
  • 7,727
  • 27
  • 30
-1

Code in UserFunction() call, is starting a new transaction, while already a transaction is going on in "upgradeneeded" listener.

So new transaction should be started, after objectStore.transaction completes.

Here is the JSFiddle : Solution is here

function UserFunction(){
    var request = window.indexedDB.open("MyTestDatabase", 3);

    request.onupgradeneeded = function(event) {
        var db = event.target.result;
        var upgradeTransaction = event.target.transaction;        
        var objectStore = db.createObjectStore("todostore", {keyPath: "timestamp"});            
        objectStore.transaction.oncomplete = function(event) {
        addIndex(db);
      };
    };
}

function addIndex(db){
    var ObjectStore = db.transaction("todostore").objectStore("todostore");
    var index = ObjectStore.createIndex("ixName", "fieldName");
}
  • Could you please share your exact code on JSFiddle, there we can refactor and resolve it easily. – Jitendra Kumar Choudhary Dec 11 '16 at 18:02
  • You can only use createIndex during a versionchange transaction, i.e. as a result of opening with a higher version and performing an upgrade. You can't use createIndex within a transaction started with db.transaction() – Joshua Bell Dec 12 '16 at 16:59