【问题标题】:update existing index keypath of an object store on indexed db upgrade在索引数据库升级上更新对象存储的现有索引键路径
【发布时间】:2015-12-10 07:32:39
【问题描述】:

我正在使用索引数据库进行离线存储。数据库有很多对象存储,每个对象存储都有索引。 IDB 索引由 name 和 keyPath(我们应用索引的 col) 属性组成。通常我们保持两个属性值相同(以便通过 col 名称轻松识别索引)。现在我的要求是索引只更改KeyPath(索引名称保持不变)

在 upgradeneeded 回调(DBOpenRequest.onupgradeneeded)中,我能够从事务中获取对象存储。

DBOpenRequest.onupgradeneeded = function(event) {
        var transaction = event.target.transaction;
        var objectStore = transaction.objectStore("objectStore Name");
        var IDBIndexObj = objectStore.index("indexName");//exception
        if(IDBIndexObj.keyPath !== "newKeyPath"){ 
            //delete index and create new index with the new keypath
        }

    };

但是对象存储只有索引的名称。当我尝试创建 IDBIndex 对象时,会引发异常,因为事务属于“versionchange”类型。 那么,如何让现有的索引键路径与新的键路径进行比较。

【问题讨论】:

    标签: indexeddb


    【解决方案1】:

    尝试以下方法:

    function onUpgradeNeeded(event) {
      var db = event.target.result;
      var storeNames = db.objectStoreNames;
      var myStore = null;
    
      if(storeNames.contains('myStoreName')) {
        myStore = event.target.transaction.objectStore('myStoreName');
      } else {
        myStore = db.createObjectStore('myStoreName', ...);
      }
    
      var indexNames = myStore.indexNames;
      var desiredKeyPathForMyIndex = ...;
    
      if(indexNames.contains('myIndexName')) {
        var myIndex = myStore.index('myIndexName');
        var currentKeyPath = myIndex.keyPath;
        if(currentKeyPath != desiredKeyPathForMyIndex) {
          myStore.deleteIndex('myIndexName');
          myStore.createIndex('myIndexName', desiredKeyPathForMyIndex);
        }
      } else {
        myStore.createIndex('myIndexName', desiredKeyPathForMyIndex);
      }
    }
    

    查看https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex,了解有关访问 IDBIndex 其他属性的更多信息。

    【讨论】:

      猜你喜欢
      • 2010-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多