IndexedDB在升级期间覆盖值

时间:2012-08-23 03:09:34

标签: javascript database html5 indexeddb

我创建了一组在升级过程中传递给IndexedDB的JSON数据。它创建了一个非常好的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 });

在此先感谢您的帮助,搜索了所有内容,无法找到解决此问题的方法。

编辑 2012年8月24日

根据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');
};

1 个答案:

答案 0 :(得分:2)

只有在找到数据库中已存在的密钥时才会覆盖数据。如果找不到密钥,则会添加密钥。

如果您想要防止第二次插入此数据或更新,则有一些解决方案:

  • 在放入数据之前,请检查是否存在任何密钥存在(获取方法)
  • 使用add方法代替put。 (当密钥已经存在时,这将导致错误。不是很好)
  • 检查旧版本的数据库是0还是空,然后才运行插入。
相关问题