3

I'm trying to forcefully update a database in IndexedDB by sending an open request with the current database's version number incremented by one with:

var openRequest = indexedDB.open("db-name", dbVariable.version + 1);

However the onupgradeneeded event is never triggered and the openRequest stays in the pending state indefinitely.

What am I doing wrong?

Is there another way to forcefully update a database in IndexedDB?

EDIT

Say I have a function connect2db which takes variable version:

function connect2db(version) {
    var openRequest = indexedDB.open("database-name", version);

    openRequest.onsuccess = function(e) {
        databaseVariable = e.target.result;
    }

    openRequest.onupgradeneeded = function(e) {
        databaseVariable = e.target.result;
        // Do schema update...
    }
}

And I have another circumstance where I'd like to update the database schema:

connect2db(databaseVariable.version + 1);

Assume darabaseVariable already exists and points to a database

When I've tried running code in this format, the onupgradeneeded event is never triggered. What could be going wrong?

  • 1
    You need to show more surrounding code, like how and when and where this is called. Calling indexedDB.open with a higher version and the same database name is how you would force an update. – Josh Aug 22 '16 at 13:11

1 Answers1

3

The problem is probably your setting of 'databaseVariable'. You can't do that in the way you seem to expect. You probably want to review or learn more about writing asynchronous code. A complete answer is very lengthy, and has already been written several times for this type of question. Consider looking at some of answers to other questions with the indexedDB tag.

Very briefly, make sure you understand how the following works:

var x = 1;
console.log(x);
setTimeout(function() {
  x = 2;
  console.log(x);
}, 0);
x = 3;
console.log(x);

Your code is written such that you expect to see 123, but this prints out 132. Make sure you understand why.

Josh
  • 17,834
  • 7
  • 50
  • 68
  • Would you mind providing resources, or would a google search of "asynchronous javascript" be sufficient? – Benjamin Spiegel Aug 23 '16 at 01:34
  • I found a different question related to Indexeddb that answered my question of updating: http://stackoverflow.com/questions/20097662/how-to-create-multiple-object-stores-in-indexeddb?rq=1 – Benjamin Spiegel Aug 23 '16 at 01:42