检查并增加 IndexedDB 的版本号。

Ric*_*non 5 javascript json indexeddb

我有一个存储大量动态数据的 IndexedDB。(静态数据已经被 Service Worker 缓存了)

我的问题是由于这些数据是动态的,我需要清除 IndexedDB 并在每次打开应用程序时将其恢复。为此,我需要增加版本号,以便触发 onupgradeneeded 事件。我想不出任何合乎逻辑的方法来做到这一点,即使在 onupgradeneeded 事件中使用以下调用,我也会得到一个未定义的答案。

e.target.result.oldversion
Run Code Online (Sandbox Code Playgroud)

我的 IndexedDB 代码如下,参数为: Key - 要存储在数据库中的 JSON 对象的名称。值 - JSON 对象本身。

function dbInit(key, value) {
// Open (or create) the database

var open = indexedDB.open("MyDatabase", 1);

console.log(value);

// Create the schema
open.onupgradeneeded = function(e) {
    console.log("Old Version: " + e.target.result.oldversion); //Undefined
    console.log("New Version: " + e.target.result.newversion); //Undefined
    var db = open.result;
    var store = db.createObjectStore("Inspections", {keyPath: "id", autoIncrement: true});
    var index = store.createIndex(key, key);
};

open.onsuccess = function() {

    // Start a new transaction
    var db = open.result;
    var tx = db.transaction("Inspections", "readwrite");
    var store = tx.objectStore("Inspections");
    var index = store.index(key);

    store.add(value);

    // Close the db when the transaction is done
    tx.oncomplete = function() {
        db.close();
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

由于此方法为多个“Key”对象多次调用,因此我需要想办法在每次打开页面时增加此版本号一次,然后将“add”调用移到 onupgradeneeded 方法之外 - 但是目前,优先级是确保它运行一次 - 增加版本号,触发 onupgradeneeded,删除当前数据,存储新数据。

提前致谢!

Jos*_*ell 5

oldVersionnewVersion性能(注意大小写)都在IDBVersionChangeEvent,而不是在IDBDatabase。换句话说,这:

console.log("Old Version: " + e.target.result.oldversion); //Undefined
console.log("New Version: " + e.target.result.newversion); //Undefined
Run Code Online (Sandbox Code Playgroud)

应该:

console.log("Old Version: " + e.oldVersion);
console.log("New Version: " + e.newVersion);
Run Code Online (Sandbox Code Playgroud)

话虽如此……您正在以一种有点非典型的方式使用模式版本控制。如果你真的想在每次打开页面时都用一个新的数据库开始,只需在打开前删除:

indexedDB.deleteDatabase("MyDatabase");
var open = indexedDB.open("MyDatabase", 1);
// An open/delete requests are always processed in the order they
// are made, so the open will wait for the delete to run.
Run Code Online (Sandbox Code Playgroud)

请注意,如果另一个选项卡持有打开的连接并且没有响应为versionchange响应删除请求而发出的事件,则排队操作(删除和打开)将被阻止。也许这对您来说是件好事 - 它会阻止两个选项卡同时在数据库上聚会。

更典型的使用模式是仅在 Web 应用程序升级且数据库架构不同时更改版本。如果您确实需要跨会话擦除数据,您可以在打开时而不是在升级时执行此操作,并使用clear()对象存储等内容。但现在我们正在进入你的应用程序的设计,听起来你已经很好地处理了。