19

I'm using IndexedDB for a test project. Here is some example code:

var indexedDB = window.indexedDB || window.webkitIndexedDB 
                ||window.mozIndexedDB||window.msIndexedDB;

  var request = indexedDB.open("mydb",2),    

  customerData=[
    {ssn:"444-44-4444",name:"Bill",age:35,email:"bill@company.com"},      
    {ssn:"555-55-5555",name:"Donna",age:32,email:"donna@home.org"}
  ];

  request.onerror = function(event){

  };
  request.onupgradeneeded = function(event) {

     var objectStore = db.createObjectStore("customers",{keyPath:"ssn"});
     objectStore.createIndex("name","name",{unique:false});
     objectStore.createIndex("email","email",{unique:true});

     for(var i in customerData){
        objectStore.add(customerData[i]);
     }
  };
  request.onsuccess = function(e) {

  };

What I don't really understand is when my request object runs onupgradeneeded instead of onsuccess (assuming there are no errors of course). Is it when no object stores exist? Or when a new db version is created?

Thanks

Josh
  • 17,834
  • 7
  • 50
  • 68
Johan
  • 35,120
  • 54
  • 178
  • 293

1 Answers1

18

According to this : https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB?redirectlocale=en-US&redirectslug=IndexedDB%2FIndexedDB_primer you have already the right answer :

onupgradeneeded is called when you change the db version : from no database to first version, first version to second version ...

onsuccess is called each time you make a new request : even if the database schemas has not been changed.

bperson
  • 1,285
  • 10
  • 19
  • 1
    Ok, but what if i dont change the db version, and still want to create a new object store? Should i do it in the onsuccess then? – Johan Aug 26 '12 at 20:21
  • 3
    I don't know if you're familiar with other database system, but you should see an object store as a table. So if you want to create a new one, the database schema is changed. As such, you should change the version of the database. So, the right place to implement it would be in the `onupgradeneeded` method. – bperson Aug 26 '12 at 20:27