2016-08-17 61 views
2

I'm開始索引資料,並沒有徹底改造使用Dexie.js https://github.com/dfahlander/Dexie.js錯誤與IndexedDB的版本和Dexie.js

我創建的數據庫輪I'm,我添加的數據,現在I'm創建通用函數獲取CSV並將數據庫填充到其他表中。

所以,或多或少我的代碼是

// Creation and populate database and first table 
var db = new Dexie("database"); 
db.version(1).stores({table1: '++id, name'}); 

db.table1.add({name: 'hello'}); 

直到這裏一切都OK現在

,在Ajax請求

db.close(); 
db.version(2).stores({table2: '++id, name'}); 
db.open(); 

db.table2.add({name: 'hello'}); 

第一次的成功,這個代碼運行一切正常,但下一次我得到這個錯誤

VersionError The operation failed because the stored database is a 
higher version than the version requested. 

如果我刪除數據庫並再次運行代碼,只有第一次工作正常。

有什麼想法?我不喜歡太多的IndexedDB版本的方式,這看起來令人沮喪,我沒有得到很多的幫助在網絡 謝謝。

編輯: 我發現了問題/錯誤/過程?如果我在修改版本之前不添加任何內容,我沒有這個問題,但有人知道這是否是正常的程序?

所以..如果這是程序,我不能添加任何dinamycally表與泛型的方法。首先是所有的聲明,然後添加值。添加值後添加表格的任何可能性?

再次編輯...我只是意識到我可以創建另一個數據庫。我會發布結果。但任何有關這個問題的信息是歡迎:)

再次編輯...我創建dinamycally另一個數據庫,每個人都很高興!

回答

4

這是因爲代碼運行第二次,你的數據庫是在第2版,但你的主代碼仍然試圖在1版本中打開它

如果不知道當前安裝的版本,嘗試打開dexie動態模式。這是通過不指定任何版本的完成:

var db = new Dexie('database'); 
db.open().then(function (db) { 
    console.log("Database is at version: " + db.verno); 
    db.tables.forEach(function (table) { 
     console.log("Found a table with name: " + table.name); 
    }); 
}); 

而動態地添加一個新表:

function addTable (tableName, tableSchema) { 
    var currentVersion = db.verno; 
    db.close(); 
    var newSchema = {}; 
    newSchema[tableName] = tableSchema; 

    // Now use statically opening to add table: 
    var upgraderDB = new Dexie('database'); 
    upgraderDB.version(currentVersion + 1).stores(newSchema); 
    return upgraderDB.open().then(function() { 
     upgraderDB.close(); 
     return db.open(); // Open the dynamic Dexie again. 
    }); 
} 

後者函數返回一個承諾要等到它使用新表之前完成。

如果您的應用程序駐留在多個瀏覽器中,其他窗口將關閉它們的數據庫連接,因此它們永遠不會相信數據庫實例隨時可以打開。您可能想要聽取db.on('versionchange')(https://github.com/dfahlander/Dexie.js/wiki/Dexie.on.versionchange)以覆蓋此默認行爲:

db.on("versionchange", function() { 
    db.close(); // Allow other page to upgrade schema. 
    db.open() // Reopen the db again. 
     .then(()=> { 
      // New table can be accessed from now on. 
     }).catch(err => { 
      // Failed to open. Log or show! 
     }); 
    return false; // Tell Dexie's default implementation not to run. 
};