我创建了一组JSON数据,这些数据在升级事件期间传递到IndexedDB。它创建了一个很好的IndexedDB数据库,看似没有问题。问题是,当您将数据库从版本1升级到版本2时,它会覆盖所有现有数据,因为它只是循环遍历JSON并应用它。
升级中必须采取某种方法来防止没有唯一密钥的新数据库项写入任何内容。我该怎么做?如下所示,将覆盖当前数据。
objectStore = event.currentTarget.transaction.objectStore('player');
objectStore.put({ key: 'non unique, but I replace my twin\'s data anyway', data: value });
在此先感谢您的帮助,已搜索了所有内容,但找不到该问题的解决方案。
编辑8/24/2012
根据Kristof关于使用get检查信息的建议,我做了一些挖掘和研究。找到答案后,我决定编写一些伪代码来帮助您。
// 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或为空,然后再运行插入。