joh*_*_72 4 javascript database client indexeddb dexie
我从 IndexedDB 开始,而不是重新发明轮子我正在使用 Dexie.js https://github.com/dfahlander/Dexie.js
我创建了数据库,添加了数据,现在我正在创建一个通用函数,该函数获取 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'});
Run Code Online (Sandbox Code Playgroud)
直到这里一切正常
现在,ajax请求成功
db.close();
db.version(2).stores({table2: '++id, name'});
db.open();
db.table2.add({name: 'hello'});
Run Code Online (Sandbox Code Playgroud)
第一次运行此代码时一切正常,但下次我收到此错误
VersionError The operation failed because the stored database is a
higher version than the version requested.
Run Code Online (Sandbox Code Playgroud)
如果我删除数据库并再次运行代码,只有第一次工作正常。
任何的想法?我不喜欢太多的 IndexedDB 版本方式,它看起来令人沮丧,而且我在网络上没有得到很多帮助,谢谢。
编辑:我发现 ¿ 问题/错误/程序?。如果我在任何版本修改之前不添加任何内容,我就没有这个问题,但是有人知道这是否是正常程序吗?
所以..如果这是我无法使用通用方法以动态方式添加任何表的过程。首先所有声明,然后添加值。添加值后是否可以添加表格?
再次编辑...我刚刚意识到我可以创建另一个数据库。我会发布结果。但是欢迎提供有关此问题的任何信息:)
再次编辑...我创建了另一个数据库,每个人都很高兴!!
这是因为第二次运行代码时,您的数据库在版本 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);
});
});
Run Code Online (Sandbox Code Playgroud)
并动态添加一个新表:
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.
});
}
Run Code Online (Sandbox Code Playgroud)
后一个函数返回一个承诺,在使用新表之前等待它完成。
如果您的应用程序驻留在多个浏览器中,则其他窗口也会关闭它们的数据库连接,因此它们永远无法信任数据库实例在任何时候都处于打开状态。您可能想听 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.
};
Run Code Online (Sandbox Code Playgroud)