如何在IndexedDB中将索引添加到预先存在的ObjectStore

时间:2016-12-11 13:05:27

标签: javascript indexeddb

我知道已经多次询问过这些问题了。但是在多次出错之后我无法找到解决方案。这是我的索引数据库的代码

    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.

我正在调用此按钮单击功能我想在单击按钮时添加带索引的索引

<button onclick="UserFunction()">createIndex</button>

2 个答案:

答案 0 :(得分:0)

您只能在版本升级期间更改数据库的架构。这样的事情似乎是合理的:

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

答案 1 :(得分:-1)

UserFunction()调用中的代码正在启动一个新事务,而事务已经在&#34; upgradeneeded&#34;监听器。

因此,在objectStore.transaction完成后,应该启动新事务。

这是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");
}
相关问题