简体   繁体   中英

IndexedDB - new version of database

My PWA uses IndexedDB to store Data.

Now im releasing Version 2.0 for it, which requires the storing of data in a third ObjectStore.

When the PWA was first released, the IndexedDB created had the version "1" like this.

var db;
var request = window.indexedDB.open("database-db", 1);

// Creating ObjectStores
request.onupgradeneeded = function(event) {
    var db = event.target.result;

    var driverTable = db.createObjectStore("driver");
    var claimTable = db.createObjectStore("claim", {
        autoIncrement: "true"
    });
};

For the Release of 2.0 i now went ahead and created another ObjectStore (language) in my "onupgradeneeded" handler and changed the version like this, hoping the IndexedDB would automatically reload itself with the new version in the background.

var db;
var request = window.indexedDB.open("database-db", 2);

// Creating ObjectStores
request.onupgradeneeded = function(event) {
    var db = event.target.result;

    var languageTable = db.createObjectStore("language");
    var driverTable = db.createObjectStore("driver");
    var claimTable = db.createObjectStore("claim", {
        autoIncrement: "true"
    });
};

Unfortunately this only works for 2 scenarios.

  1. I open the PWA in Chrome on my desktop and delete the IndexedDB in the Application-Tab of DevTools and reload the page afterwards.

  2. I never opened the site before and therefore have no IndexedDB installed in my browser.

The problem is, that i already have existing users and they have no option of deleting the IndexedDB on their smartphones, apart from that not being an option in terms of user-experience.

Is there a better way to approach this?

Thanks in advance.

Yes there are better ways to approach this. You can do version number based checks, or just check if things exist or not. Here is some simple example code that checks if a store exists and only creates a store if it does not exist.

function myOnUpgradeNeeded(event) {
  const db = event.target.result;

  if (db.objectStoreNames.contains('mystorename') {
    console.log('mystorename already exists, not recreating');
  } else {
    console.log('mystorename does not exist,  creating');
    db.createObjectStore('mystorename');
  }
}

If you want to remove all objects from a store on upgrade, then you can add logic that says that if the table exists, you can clear it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM