2016-08-17 90 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. 
};