Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and why is the onupgradeneeded method called in indexedDB?

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:"[email protected]"},      
    {ssn:"555-55-5555",name:"Donna",age:32,email:"[email protected]"}
  ];

  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

like image 348
Johan Avatar asked Aug 26 '12 19:08

Johan


1 Answers

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.

like image 138
bperson Avatar answered Oct 21 '22 15:10

bperson