Create a DB:
Import IDB from ' IDB ';varDbpromise = Idb.open (' test-db ', 2,function(upgradedb) {Switch(upgradedb.oldversion) { Case0: //Keyval Store is already created at version 1 varKeyvalstore = Upgradedb.createobjectstore (' Keyval ')); Keyvalstore.put ("World", "Hello"); Case1: //New versionUpgradedb.createobjectstore (' People ', {keypath: ' name ')}); }});
The oldversion switch between old DB and new db. So here we create a new people db.
ReadWrite:
Dbpromise.then (function(db) {vartx = Db.transaction (' People ', ' ReadWrite '); varPeoplestore = Tx.objectstore (' People ')); Peoplestore.put ({name:"John",//name is the keyAge:23, Favoriteanimal:' Cat ' }); Peoplestore.put ({name:"Joe",//name is the keyAge:21, Favoriteanimal:' Cat ' }); Peoplestore.put ({name:"Jie",//name is the keyAge:22, Favoriteanimal:' Dog ' }); Peoplestore.put ({name:"Jay",//name is the keyAge:24, Favoriteanimal:' Dog ' }); returnTx.complete;}). Then (function() {Console.log ("People is added");}); Dbpromise.then (function(db) {vartx = Db.transaction (' People '); varPeoplestore = Tx.objectstore (' People ')); returnPeoplestore. GetAll ();}). Then (function(People) {console.table (people);});
Group by:
To does gourp by we need to create INDEX:
Import IDB from ' IDB ';varDbpromise = Idb.open (' test-db ', 3,function(upgradedb) {Switch(upgradedb.oldversion) { Case0: //Keyval Store is already created at version 1 varKeyvalstore = Upgradedb.createobjectstore (' Keyval ')); Keyvalstore.put ("World", "Hello"); Case1: //New versionUpgradedb.createobjectstore (' People ', {keypath: ' name ')}); Case2: varPeoplestore = UpgradeDb.transaction.objectStore (' People ')); Peoplestore.createindex (' Animal ', ' favoriteanimal '); }});
Group by Animal:
Dbpromise.then (function (db) { var tx = db.transaction (' People '); var peoplestore = Tx.objectstore (' People '); var animalindex = Peoplestore.index (' animal '); // return Animalindex.getall ();//All the animals return // Only Cat}). Then (function (people) { console.table (people);});
[PWA] 13. New db and Object store