【问题标题】:How do I check if a store key exists in IndexedDB?如何检查 IndexedDB 中是否存在存储键?
【发布时间】:2021-06-11 06:06:00
【问题描述】:

如果已存在,我想检查并更新 indexeddb 存储中的项目数量。这就是我目前使用 Dexie 将商品添加到商店的方式

    async function addNfetch (itemdata) {
        
        return new Promise((resolve, reject) => {
         db.table('cartitems')
        .add(itemdata)
        .then(() =>{ 
            db.table("cartitems").toArray().then((itemArry) => {
                console.log("item array ", itemArry)
    
                resolve(itemArry)
             })
        })
        .catch(error => {
            console.log(error);
          });
    
      })
    }

上述函数只在对象键已经存在的情况下添加并抛出错误

DexieError {_e:错误 在 getErrorWithStack (http://localhost:3000/static/js/0.chunk.js:14551:10) 在新的 Dex...,名称:“ConstraintError”,消息:“对象存储中已存在密钥。↵ ConstraintError:对象存储中已存在密钥。”,内部:DOMException:对象存储中已存在密钥。,_promise: DexiePromise,

要检查密钥是否存在,我只能考虑使用 error.message。

  if (error.message == "Key already exists in the object store"){
     // then object exist 
  }

有没有更好的方法来检查存储密钥是否已经存在,以便我可以更新而不是覆盖它。

【问题讨论】:

    标签: javascript indexeddb dexie


    【解决方案1】:
    function addNfetch (itemdata) {
      return db.table('cartitems').put(itemdata);
    }
    

    put() 与 add() 类似,但如果条目已存在则更新它。

    另外,请注意:您无需创建新的 Promise() 即可调用基于 Promise 的 API:s。这个例子不需要异步,因为它只调用一个 API 方法。也可以是:

    async function addNfetch (itemdata) {
      return await db.table('cartitems').put(itemdata);
    }
    

    但是正如你所看到的,在这个示例中它并没有真正简化任何事情。

    【讨论】:

      猜你喜欢
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      • 2011-09-08
      • 1970-01-01
      • 2011-03-18
      相关资源
      最近更新 更多