如何更改IndexedDB索引中对象的值?

ogq8wdun  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(2)|浏览(331)

是否可以在不克隆、删除或添加新条目的情况下更新IndexedDB索引中的对象值?理论上,类似以下代码段的代码段可以做到这一点,尽管在put得到确认之前,它可能不会delete。但在我看来,这似乎有点矫枉过正。在它上面进行任何错误处理都将是一场噩梦。

const objectStore = db.transaction([objectStoreName], 'readwrite')
  .objectStore(objectStoreName);

const requestGet = objectStore.get(index);
requestGet.onsuccess = (event: any) => {
  const value = event.target.result.value // Store old value
  const requestDelete = objectStore.delete(index);
  requestDelete.onsuccess = (event: any) => {
    const requestPut = objectStore
      .put({index: 'New Index Value', value: value}); // Put back using new index         
  };
};
syqv5f0l

syqv5f0l1#

您无法直接变更对象存放区索引中的值。您可以变更对象存放区中对象的值,IndexedDB会将您的变更传播到相关索引。索引基本上是只读的。

6rqinv9w

6rqinv9w2#

这是可能的,因为您指定了索引,否则可能需要其他逻辑。
正如你应该知道的,IDBObjectStore有一个方法**.put()**,它将接收两个参数。使用它你可以放置一个新值或更新一个值。
放置(项,键)项:您要放置/更新的项关键字:可选:您要更新的项目的主要对象存储密钥(如uuid、随机数,简称...)。
编码:

//This is an example only.
    //Let's think that we have an object store into our IndexDB 'user', where object store is called by user-data: 
    //#  Key              Value
    //0   1     { username: 'John Doe' } 

    //Here, we are receiving the 'success' result from an indexedDB.open(), and using its result with a promise.
    dbPromise.then(db => {
            //Getting the transaction
            const transaction = db.transaction('user-data', 'readwrite')
            //Getting the objectStore with the data, the same object store before.
            const store = transaction.objectStore('user-data')
            //Getting the key's object store, in the other other words, this is the key you define when you create you objectStore, with createObjectStore. In this example, I've used 'autoIncrement: true'
            const query = store.get(1)
            
            //Getting the query result with a success listener.
            query.addEventListener('success', event => {
                const { ['result']: user } = event.target
                user.productsIntoCart.push(newItem)
                
                //With this, we will be able to change the object store value.  
                user.username = 'Jane Doe'
                store.put(user, 1)
            })
            query.addEventListener('error', event => console.error(event))
            transaction.addEventListener('complete', () => db.close())
        })
        
    //#  Key              Value
    //0   1     { username: 'Jane Doe' }

您可以在MDN IDBObjectStore.put文档中查看所需的更多详细信息。IDBObjectStore

相关问题