[PWA] 13. New db and object store
2024-09-10 07:50:03
Create a db:
import idb from 'idb'; var dbPromise = idb.open('test-db', 2, function (upgradeDb) {
switch (upgradeDb.oldVersion) {
case 0:
// keyval store is already created at version 1
var keyValStore = upgradeDb.createObjectStore('keyval');
keyValStore.put("world", "hello");
case 1:
// new version
upgradeDb.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) {
var tx = db.transaction('people', 'readwrite');
var peopleStore = tx.objectStore('people'); peopleStore.put({
name: "John", // name is the key
age: 23,
favoriteAnimal: 'cat'
});
peopleStore.put({
name: "Joe", // name is the key
age: 21,
favoriteAnimal: 'cat'
});
peopleStore.put({
name: "Jie", // name is the key
age: 22,
favoriteAnimal: 'dog'
});
peopleStore.put({
name: "Jay", // name is the key
age: 24,
favoriteAnimal: 'dog'
});
return tx.complete;
}).then(function () {
console.log("People are added");
}); dbPromise.then(function (db) {
var tx = db.transaction('people');
var peopleStore = tx.objectStore('people');
return peopleStore.getAll();
}).then(function (people) {
console.table(people);
});
Group By:
TO do gourp by we need to create index:
import idb from 'idb'; var dbPromise = idb.open('test-db', 3, function (upgradeDb) {
switch (upgradeDb.oldVersion) {
case 0:
// keyval store is already created at version 1
var keyValStore = upgradeDb.createObjectStore('keyval');
keyValStore.put("world", "hello");
case 1:
// new version
upgradeDb.createObjectStore('people', {keyPath: 'name'});
case 2:
var peopleStore = 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 animalIndex.getAll('cat'); // only cat
}).then(function (people) {
console.table(people);
});
最新文章
- iOS 之消息推送(个推)---个人小结
- 在Application中集成Microsoft Translator服务之开发前准备
- C#------各种常见错误解决方法
- 【C】 04 - 表达式和语句
- 关于停止AsyncTask和Thread的问题
- js的设计模式
- shell脚本摘要
- 002 The Variables In Csharp
- Python - re - 正则表达式 - 怎么用
- 恩布企业 IM 安卓端 1.3,服务端 1.12 公布
- 主存与Cache的地址映射
- 微信内点击链接或扫描二维码可直接用外部浏览器打开H5链接的解决方案
- 理解MySql的锁&;事务隔离级别
- 外显子分析思路总结(Exome Sequencing Analysis review)
- 配置本地无密码 SSH登录远程服务器
- C语言学习感受
- Oracle联合多个子查询(inner join)
- 2018.10.24 bzoj2064: 分裂(状压dp)
- jquery如何获取元素的滚动高度
- ArcGIS API for Silverlight——小滑块