【问题标题】:Check if indexedDB Index already exists检查 indexedDB 索引是否已经存在
【发布时间】:2016-08-11 02:31:05
【问题描述】:

我想在 onupgradeneeded 中更新我的 indexeddb 数据库的 objecstore 之一。我想检查一下,如果这个 objecstore 中存在这个索引,那么就不需要做任何更改。但如果不是,我想更新它的索引。

【问题讨论】:

    标签: indexeddb


    【解决方案1】:
        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', ...);
          }
    
        };
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-04
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2015-05-05
    相关资源
    最近更新 更多