Is there a way to guarantee the existence of object stores in an indexedDB without changing the version number?
Context:
One of my users has an indexedDB set to the same version as everyone else, but with no object stores. I’ve no idea how they did it so I can’t predict if it will happen again and I don’t know how widespread the problem could be out in the public arena.
I tried using the following code to rebuild the missing objectStore
this.request = window.indexedDB.open(this.dbName, this.DB_VERSION);
this.request.onsuccess = (event) => {
const database = event.target.result;
if (!database.objectStoreNames.contains(store)) {
const newStore = database.createObjectStore(store, {keyPath: 'key'});
newStore.createIndex('expiry_idx', 'exp');
}
}
but the browser is saying I can’t run createObjectStore unless I am in the onupgradeneeded event. At this point the database is not being upgraded. This user and everyone else is on version 5. I could change the code to try to open v6 and force an upgrade that repairs it, but for all I know someone else could corrupt v6.
2
Answers
Since you clarified that
here means
I guess the answer is
No
Yes you can check if it exists using the IDBDatabase: objectStoreNames property. It returns a DOMStringList with which you can call the
contains()
method. But you cannot create an object store (if it doesn’t already exist) without a version upgrade.There is an extremely hacky way to do it, if the database is small enough. Read all the data into memory, delete the old database, create the new database with the correct object stores and the correct version, and then write all the data to it.