skip to Main Content

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


  1. Since you clarified that

    …guarantee the existence of object stores in an indexedDB without changing the version number?

    here means

    create … if it does not exist

    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.

    This method can be called only within a versionchange transaction.

    IDBDatabase: createObjectStore() method

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search