6

Can anybody tell me how to add a new objectstore to an existing indexeddb instance which has a version number in it. When I try to create a new version existing object stores are getting deleted.

I have a version '1', which has around 10 object stores with data. When I try to open the same database with new version number, I lost the current data and object stores.

here is what I have tried.

var _upRequest = indexedDB.open("employees");

    _upRequest.onsuccess = function (e) {
        var thisDb = e.target.result;
        var version = parseInt(thisDb.version)+1;
        thisDb.close();
        var openRequest = indexedDB.open("employees", version);

        //handle setup, this will be run by Firefox
        openRequest.onupgradeneeded = function (e) {
            console.log("running onupgradeneeded");
            var thisDb = e.target.result;

            //Create Employee
            if (!thisDb.objectStoreNames.contains("employee")) {
                console.log("I need to make the employee objectstore");
                var objectStore = thisDb.createObjectStore("employee", { keyPath: "id", autoIncrement: true });
                objectStore.createIndex("searchkey", "searchkey", { unique: false });
            }
            thisDb.close();
        }

        openRequest.onsuccess = function (e) {

            db = e.target.result;

            db.onerror = function (e) {
                alert("Sorry, an unforseen error was thrown.");
                console.log("***ERROR***");
                console.dir(e.target);
            }

            db.close();
        }
    }
2
  • Why are you using setVersion? Isn't that deprecated? What resource did you use that suggested using setVersion? Commented Aug 9, 2016 at 13:42
  • @Josh That was a code reference I have taken from another link. It wasn't working for me. So I have removed from here and updated the question Commented Aug 9, 2016 at 13:59

2 Answers 2

8

I don't have a direct answer but your code as it is currently written seems strange to me.

One thing I would try first is properly binding onupgradeneeded, onerror, and not closing the database prematurely.

Do not do this:

var request = indexedDB.open();
request.onsuccess = function() {
  request.onupgradeneeded = function() {};
};

Do this instead:

var request = indexedDB.open();
request.onsuccess = function() {};
request.onupgradeneeded = function() {};

Similarly, bind onerror immediately, not only later in onupgradeneeded or onsuccess, like this:

var request = indexedDB.open();
request.onsuccess = function() {};
request.onupgradeneeded = function() {};
request.onerror = function() {};

When indexedDB.open detects a higher version or first version, it will dispatch an upgradeneeded event, wait for the implied 'versionchange' transaction to complete, and then dispatch a success event.

I can't quite make sense of your code. I am not sure why you are opening a connection, closing it, then opening a second connection, then late binding the upgradeneeded handler.

This is all you need to do to add an object store and then access it:

var request = indexedDB.open('name', aNumberGreaterThanTheCurrentVersion);
request.onupgradeneeded = function(event) {
  console.log('Performing upgrade');
  var db = event.target.result;
  console.log('Creating object store');
  db.createObjectStore('mystore');
};

request.onsuccess = function(event) {
  console.log('Connected to database');
  var db = event.target.result;
  var tx = db.transaction('mystore');
  var store = tx.objectStore('mystore');
  console.log('Doing something with store "mystore"');
  // ...
  console.log('Finished doing something, now closing');
  db.close();
};

request.onerror = console.error;

Another note. indexedDB produces different types of errors, and it is important to distinguish them. request.onerror doesn't "throw" an exception as your log message suggests. Instead, what happened is that indexedDB dispatched an error event. Dispatched error events are not thrown. Now, with that aside, several of indexedDB's functions can throw exceptions. These need to be caught by a try/catch block. You won't even see a dispatched error event. You will get an actual script error that halts execution and will automatically appear in the console with a slightly-informative message.

Sign up to request clarification or add additional context in comments.

5 Comments

@Josh- My requirement is On load of my application(Angularjs SPA) I have set of tables will be created. On load of an another view or screen I am trying to add an objectstore to an existing database which already have some set of tables in it. Per my understanding for adding a new objectstore I need to increase the version number of the existing database and add objectstore in onupgradeneeded function.
The solution you have provided just works fine with just html +javascript but not with html+javascript+angularjs
Then this is a problem with Angular or your use of Angular. I suggest you flag this using the appropriate angular tag and hope that the Angular folks can help you. I suggest you clean up and clarify the code before asking because you are probably not going to receive a helpful response.
One more question. When I open the db with newer version. it is not triggering onupgradeneeded but it does onblocked. in that case how do add a new objectstore ?
Very late, randomly noticed this, but upgradeneeded is triggered by calling indexedDB.open on a database with a higher version number.
1
let OpenReq = indexedDB.open( 'dbName', version );
OpenReq.onupgradeneeded = function( e )
{
    let db = e.target.result;
    db.objectStoreNames.contains( "myStore" ) || db.createObjectStore( "myStore" );
}

if you have an exist db with version 1, run above code with version = 2 will remain the exist stores.

1 Comment

Another way is to check old version: if (event.oldVersion < 1) { db.createObjectStore( 'myStore') }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.