javascript - 如何在已经存在的 indexedDB 中的已经存在的 objectStore 中“放置”新值?
问题描述
我把自己绑在了结中,试图更新 in 中的一系列四个objectStore
条目indexedDB
。
这就是我想要实现的(在伪代码中):
let myDatabase = indexedDB('myDatabase', 1);
let myObjectStore = myDatabase.myObjectStore;
myObjectStore.entry1 = 'newValue1';
myObjectStore.entry2 = 'newValue2';
myObjectStore.entry3 = 'newValue3';
myObjectStore.entry4 = 'newValue4';
但是,当然,这不是那么简单的事情。
我知道我需要使用put
. 但是,尽管尝试了许多方法,但我无法走得更远。
在第一次创建时,我已经成功地设置和填充了:objectStore
indexedDB
// SET UP VALUES OBJECT
let valuesObject = {
entry1 : 'a',
entry2 : 'b',
entry3 : 'c',
entry4 : 'd'
};
// SET UP INDEXED DATABASE
const setUpIndexedDatabase = (valuesObject) => {
let database
const databaseVersion = 1;
const databaseName = \'myDatabase\';
const databaseOpenRequest = indexedDB.open(databaseName, databaseVersion);
databaseOpenRequest.onupgradeneeded = () => {
database = databaseOpenRequest.result;
let myObjectStore = database.createObjectStore('myObjectStore');
myObjectStore.transaction.oncomplete = () => {
let objectStoreValues = database.transaction('Values', 'readwrite').objectStore('Values');
const valuesEntries = Object.entries(valuesObject);
for (let i = 0; i < valuesEntries.length; i++) {
objectStoreValues.add(valuesEntries[i][1], valuesEntries[i][0]);
}
}
}
databaseOpenRequest.onsuccess = () => {
database = databaseOpenRequest.result;
// >>> THIS IS THE BIT THAT I NEED TO WRITE <<<
database.close();
}
}
setUpIndexedDatabase(valuesObject);
到目前为止,一切都很好。onupgradeneeded
如果尚不存在数据库,则上面的代码会触发该事件,这会创建myObjectStore
并使用四个键值对填充它。
但是,如果数据库确实存在并且已经包含myObjectStore
,那么我使用的每个代码变体都put
无法更新键的值并返回各种错误——而且通常根本没有错误。
我要做的就是更新数据库中的值。
put
我认为问题是当数据库版本保持不变并且onupgradeneeded
不触发时,我不知道如何正确使用。
解决方案
如果要更新数据库中已经存在的值,可以使用以下代码进行操作(例如,我正在更新entry1
条目):
databaseOpenRequest.onsuccess = function(event) {
db = event.target.result;
const objectStore = db.transaction('myObjectStore', 'readwrite').objectStore('myObjectStore');
const request = objectStore.put('e', 'entry1');
request.onerror = function(event) {
// There was an error while updating.
};
request.onsuccess = function(event) {
// The update was successful.
};
}
推荐阅读
- python - 是否可以延迟作为函数调用一部分的表达式的评估?
- c++ - 如何在 Microsoft Visual C++ 项目中添加箭头键作为修饰键
- python - 如何让我的 2 bot 玩家井字游戏程序确定是否为平局?
- java - android中的链式LiveData转换
- r - 定位和减少线标签
- javascript - 从 React Native 中的 blob 获取图像尺寸
- angular - 在 Angular 的 CanActivate 路由保护中读取 cookie
- python - 如何将具有多个 python 脚本和图像的 pygame 程序转换为 exe?
- solidity - node_modules 中缺少开放的 zeppelin 合约
- html - CSS 未按预期出现或运行