idb function(upgradeDb) not called when database exists

378 Views Asked by At

There's a common example code (modified version listed below) showing how to create object stores when opening an idb database. The idb.open callback function checks if each object store exists and creates it in case it's missing.

I've noticed that this function is ONLY called when the database doesn't exist, so what's the reason of checking each object store existence if the function is only called when these object stores surely not exist?

class indexeddb {

    static OpenIDB() {

        return idb.open('dbName', 1, function(upgradeDb) {      

            if (!upgradeDb.objectStoreNames.contains('objectStore1')) {
                const store1 = upgradeDb.createObjectStore('objectStore1', {keyPath: 'someKey'});
            }
            if (!upgradeDb.objectStoreNames.contains('objectStore2')) {
                const store2 = upgradeDb.createObjectStore('objectStore2', {keyPath: 'someKey'});
            }
            if (!upgradeDb.objectStoreNames.contains('objectStore3')) {
                const store3 = upgradeDb.createObjectStore('objectStore3', {keyPath: 'someKey'});
            }

        });

    };   //class continues...

Why I need this? I need to add a new object store to an existing database in my web app, but it seems impossible.

2

There are 2 best solutions below

0
Tom On BEST ANSWER

Incrementing database version solved the case. The process of posting your question on StackOverflow has an enlightening power. I'm leaving it here in case anyone else gets stuck in his own box.

1
Pavel Popov On

Seems like the version number has to be whole number. In my case changing it to from 1 to 1.1 didn't call upgrade but 1 to 2 did.