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



是否可以在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         
};
};

不能直接更改对象存储索引中的值。您可以更改对象存储中对象的值,IndexedDB会将您的更改传播到相关索引。索引本质上是只读的。

由于您指定了索引,因此可能需要其他逻辑。

如您所知,IDBObjectStore有一个方法.put((,它将接收两个参数。使用它,您可以PUT一个新值或UPDATE一个值。

IDBObjectStore.put(项,键(item:要放置/更新的项目key:operational:您要更新的项目的主对象存储密钥(例如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

最新更新