Javascript IndexedDB在升级期间覆盖值
我已经创建了一组JSON数据,这些数据在升级事件期间被传递到IndexedDB。它创建了一个非常好的IndexedDB数据库,看起来没有问题。问题是,当您将数据库从版本1升级到版本2时,它会覆盖所有现有数据,因为它只是循环通过JSON并应用它 升级过程中必须有某种方法防止没有唯一密钥的新数据库项写入任何内容。我该怎么做?因为以下内容只是覆盖了当前数据Javascript IndexedDB在升级期间覆盖值,javascript,database,html,indexeddb,Javascript,Database,Html,Indexeddb,我已经创建了一组JSON数据,这些数据在升级事件期间被传递到IndexedDB。它创建了一个非常好的IndexedDB数据库,看起来没有问题。问题是,当您将数据库从版本1升级到版本2时,它会覆盖所有现有数据,因为它只是循环通过JSON并应用它 升级过程中必须有某种方法防止没有唯一密钥的新数据库项写入任何内容。我该怎么做?因为以下内容只是覆盖了当前数据 objectStore = event.currentTarget.transaction.objectStore('player'); obje
objectStore = event.currentTarget.transaction.objectStore('player');
objectStore.put({ key: 'non unique, but I replace my twin\'s data anyway', data: value });
提前感谢您的帮助,搜索了所有内容,无法找到此问题的解决方案
编辑2012年8月24日
根据克里斯托夫关于使用get检查信息的建议,我做了一些挖掘和研究。找到答案后,我决定写一些psuedo代码来帮助你
// Create the get request inside your upgrade
var tableData = event.currentTarget.transaction.objectStore('your table name');
var getData = tableStore.get('your key');
// Run the get request
getData.onsuccess = function (e) {
var result = e.target.result;
// Immediately exit if the current result is not undefined
if (result !== undefined) {
return;
}
// Note, you may or may not need a closure to write data in the callback
// See here for more info on closures in events http://stackoverflow.com/questions/3495679/passing-parameters-in-javascript-onclick-event#answer-3495722
tableStore.add('data to add');
};
只有在发现数据库中已经存在的密钥时,才能覆盖数据。如果找不到密钥,只需添加 如果要防止再次插入或更新此数据,有一些解决方案:
- 在放入数据之前,检查该键是否存在(get方法)
- 使用add方法而不是put方法。(当密钥已经存在时,这将导致错误。不是很好)
- 检查数据库的旧版本是否为0或无,然后运行insert