8

I have this simple example code:

var request = mozIndexedDB.open('MyTestDatabase');
request.onsuccess = function(event){
  var db = event.target.result;
  var request = db.setVersion('1.0');
  request.onsuccess = function(event){
    console.log("Success version.");
    if(!db.objectStoreNames.contains('customers')){
      console.log("Creating objectStore");
      db.createObjectStore('customers', {keyPath: 'ssn'});
    }
    var transaction = db.transaction([],  IDBTransaction.READ_WRITE, 2000);
    transaction.oncomplete = function(){
      console.log("Success transaction");
      var objectStore = transaction.objectStore('customers');
    };
  };
};

I am getting this:

A mutation operation was attempted on a database that did not allow mutations." code: "6

on line

var objectStore = transaction.objectStore('customers');

Can't figure out - what do I do wrong?

Josh
  • 17,834
  • 7
  • 50
  • 68
Aleksandr Motsjonov
  • 1,230
  • 3
  • 14
  • 25

3 Answers3

7

You can create or delete an object store only in a versionchange transaction

see: https://developer.mozilla.org/en-US/docs/IndexedDB/IDBDatabase

j0k
  • 22,600
  • 28
  • 79
  • 90
cyong
  • 73
  • 1
  • 4
5

I think I found the answer. I shouldn't access objectStore inside oncomplete. I just need to do it after making new transaction. Right way is this:

var transaction = db.transaction([],  IDBTransaction.READ_WRITE, 2000);
    transaction.oncomplete = function(){
      console.log("Success transaction");
    };
var objectStore = transaction.objectStore('customers');

Btw, this is how exactly Mozilla's MDN shows. https://developer.mozilla.org/en/IndexedDB/Using_IndexedDB#section_10

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
Aleksandr Motsjonov
  • 1,230
  • 3
  • 14
  • 25
  • This question is related to [this](http://stackoverflow.com/questions/11149388/indexeddb-differences-between-onsuccess-and-oncomplete) regarding the differences between `onsuccess` and `oncomplete` – user1460015 Jan 25 '13 at 16:57
0

I didn't try that code but judging by the documentation you shouldn't pass an empty list as first parameter to db.transaction() - it should rather be db.transaction(["customers"], ...) because you want to work with that object store.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
  • 2
    Thanks, but It doesn't metter. I removed it for simplicity. So "customers" in scope doesn't change anything. Anyway, I think empty array is ok: "If this parameter is unspecified, **empty**, or null, then the scope of the transaction is the entire connected database." – Aleksandr Motsjonov Sep 04 '11 at 19:24