2016-08-11 24 views
0

Ich möchte einen der Objecstores meiner indexeddb Datenbank im onupgradeeneded aktualisieren. Ich möchte überprüfen, ob dieser Index in diesem Objekt vorhanden ist, dann müssen keine Änderungen vorgenommen werden. aber wenn ich nicht will, muss ich den index aktualisieren.Überprüfen, ob der indexedDB Index bereits existiert

Antwort

4
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', ...); 
    } 

}; 
+0

Große Antwort, Danke! – user6333296

+0

Wo ist die offizielle (oder inoffizielle) Dokumentation für 'contains'? Ich habe alle möglichen Quellen durchsucht (MDN, w3.org usw.) und [diese Frage] (http://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes- Ein-Objekt-in-Javascript), aber ich kann keine native Methode finden. Und wo kann ich über 'contains' nachlesen? –

+1

https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/indexNames und https://developer.mozilla.org/en-US/docs/Web/API/DOMStringList – Josh

Verwandte Themen