Errors with IndexedDB versions and Dexie.js Errors with IndexedDB versions and Dexie.js database database

Errors with IndexedDB versions and Dexie.js


That is because the second time the code runs, your database is on version 2, but your main code still tries to open it at version 1.

If not knowing the current version installed, try opening dexie in dynamic mode. This is done by not specifying any version:

var db = new Dexie('database');db.open().then(function (db) {    console.log("Database is at version: " + db.verno);    db.tables.forEach(function (table) {        console.log("Found a table with name: " + table.name);    }); });

And to dynamically add a new table:

function addTable (tableName, tableSchema) {    var currentVersion = db.verno;    db.close();    var newSchema = {};    newSchema[tableName] = tableSchema;    // Now use statically opening to add table:    var upgraderDB = new Dexie('database');    upgraderDB.version(currentVersion + 1).stores(newSchema);    return upgraderDB.open().then(function() {        upgraderDB.close();        return db.open(); // Open the dynamic Dexie again.    });}

The latter function returns a promise to wait until it's done before using the new table.

If your app resides in several browsers, the other windows will get their db connection closed as well so they can never trust the db instance to be open at any time. You might want to listen for db.on('versionchange') (https://github.com/dfahlander/Dexie.js/wiki/Dexie.on.versionchange) to override the default behavior for that:

db.on("versionchange", function() {    db.close(); // Allow other page to upgrade schema.    db.open() // Reopen the db again.        .then(()=> {           // New table can be accessed from now on.        }).catch(err => {           // Failed to open. Log or show!        });    return false; // Tell Dexie's default implementation not to run.};