【问题标题】:Errors with IndexedDB versions and Dexie.jsIndexedDB 版本和 Dexie.js 的错误
【发布时间】:2016-12-24 08:33:06
【问题描述】:

我从 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'});

到这里一切正常

现在,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 版本的方式,它看起来很令人沮丧,而且我在网络上没有得到很多帮助 谢谢。

编辑: 我发现了¿问题/错误/程序?如果我在任何版本修改之前不添加任何内容,我就没有这个问题,但是有人知道这是否是正常程序?

所以.. 如果这是我无法使用通用方法动态添加任何表格的过程。首先是所有声明,然后添加值。添加值后是否可以添加表格?

再次编辑...我刚刚意识到我可以创建另一个数据库。我会发布结果。但欢迎提供有关此问题的任何信息:)

再次编辑...我创建了另一个数据库,每个人都很高兴!

【问题讨论】:

    标签: javascript database client indexeddb dexie


    【解决方案1】:

    那是因为代码第二次运行时,您的数据库是版本 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.
    };
    

    【讨论】:

      猜你喜欢
      • 2018-04-07
      • 2021-01-20
      • 2016-07-31
      • 2018-03-16
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      相关资源
      最近更新 更多