[PWA] 13. New db and object store

本文介绍了使用IDB进行数据库创建、读写操作,并通过案例展示了如何实现数据分组和查询,强调了版本升级和数据安全性的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
});

转载于:https://www.cnblogs.com/Answer1215/p/5503850.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值