javascript - Adding an index to an existing object store in IndexedDB -
how add index created object store, within upgrade needed event?
doing on new object store documented:
request.onupgradeneeded = function(event) { var db = event.target.result; var objectstore = db.createobjectstore("my-store", { keypath: "id" } ); objectstore.createindex("idx_name", "index_this", { unique: false }); };
but how can add index object store created?
request.onupgradeneeded = function(event) { var db = event.target.result; if (!db.objectstorenames.contains("my-store")) { var objectstore = db.createobjectstore("my-store", { keypath: "id" } ); } var mystore = ?????????????; if (!mystore.indexnames.contains("idx_name")) { mystore.createindex("idx_name", "index_this", { unique: false }); } };
you want retrieve reference object store transaction implicitly provided within scope of onupgradeneeded function.
function onupgradeneeded(event) { var request = event.target; var tx = request.transaction; var store = tx.objectstore('store-name'); store.createindex(...); }
keep in mind have rewrite onupgradeneeded function attempt store if has been created, , attempt create index if has not yet been created. there couple of ways of doing that. 1 use version number. can test against old version existed before upgrade, or new/current version. e.g. use event.oldversion
if want. alternatively, can test if store exists , separately test if index exists, looking store name using db.objectstorenames.contains
, , looking index name in store.indexnames.contains
.
Comments
Post a Comment