Getting object store already exists inside onupgradeneeded

Viewed 4373

My code is as follows (usually naming convention for the well-known objects):

var DBOpenRequest = window.indexedDB.open("messages", 6);
//...
DBOpenRequest.onupgradeneeded = function(event) { 
  console.log("Need to upgrade.");
  var db = event.target.result;
  console.log(db);

  db.onerror = function(event) {
     console.log("Error upgrading.");
  };

  // Create an objectStore for this database
  var objectStore = db.createObjectStore("messages", { keyPath: "id", autoIncrement: true });
    };

This ran fine for versions 3 and 4. When it came to version 5, I get the error:

Failed to execute 'createObjectStore' on 'IDBDatabase': An object store with the specified name already exists. at IDBOpenDBRequest.DBOpenRequest.onupgradeneeded

Isn't the createObjectStore operating on a new version of the database which is empty? How do I fix the error?

I happened to log the db object and the details are below:

enter image description here

I am curious why the version number is different in the summary line and when expanded.

2 Answers

The best way to upgrade the DB is checking if the store name is already there. In this example I'm using https://npmjs.com/idb

openDB('db-name', version, {
  upgrade(db, oldVersion, newVersion, transaction) {
    if(!db.objectStoreNames.contains('messages')) {
      db.createObjectStore('messages', { keyPath: "id", autoIncrement: true })
    }
  }
})

If you need to check if an indexName already exist, you can get the objectStore and check for the indexNames property if it contains the indexName you need.

openDB('db-name', version, {
  upgrade(db, oldVersion, newVersion, transaction) {
    const storeName = transaction.objectStore('storeName')
    if(!storeName.indexNames.contains('indexName')) {
        storeName.createIndex('indexName', 'propertyName', { unique: false });
    }
  }
})

Using indexDB API with indexNames and objectStoreNames to check if something is either there or not makes my code way more reliable and easy to maintain, it is also briefly mentioned on Working with IndexDB Using database versioning

Related