You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重启应用后DexieDB已创建表无法通过db.tableName访问求助

DexieDB重启后动态创建的表无法通过db.tableName引用的问题

我正在开发一款工具,可将用户的Tiled游戏场景(JSON格式)转换为DexieDB数据库,预期游戏启动时完成JSON转换,转换后无需重复操作。但遇到了DexieDB的异常问题:重启应用并重新打开数据库后,已创建的表无法通过db.tableName的格式直接引用,但在db.storeNames和_alltables属性中仍能看到这些表的存在。

客户端调用方式

const spatialdb = new SpatialDB() // 创建DexieDB实例
await spatialdb.init() // 初始化数据库
await spatialdb.convertMap(filepath) // 按需转换JSON

我的库示例代码

程序运行初期会创建converted_maps表,用于记录所有已成功转换的JSON文件名:

export default class SpatialDB {
  static instance;
  constructor() { // 单例模式
    if (!SpatialDB.instance) {
      SpatialDB.instance = this;
      this.db = new Dexie(DB_NAME);
    }
    return SpatialDB.instance;
  }
  async init() {
    // 创建数据库初始 schema
    if (this.db.verno < 1) {
      const databaseExists = await Dexie.exists(DB_NAME);
      if (!databaseExists) {
        await this.db.version(1).stores({ converted_maps: "map_name" });
      } else {
        await this.db.open();
      }
    }
  }
  async convertMap(path) {
    const mapName = this._getPathFileName(path);

    const isConverted = await this.db.converted_maps
      .where("map_name")
      .equals(mapName)
      .toArray();

    const needToConvert = Array.isArray(isConverted) && isConverted.length == 0;

    if (needToConvert) {
      // 转换地图,完成后将该地图添加到已转换表中
      // await this._convertTiledToMap(path);
      await this.db.converted_maps.add({ map_name: mapName });
    }
  }
  /**
   * @param {string} path
   * @return 返回给定路径对应的JSON文件名
   */
  _getPathFileName(path) {
    const parts = path.split("/");
    const tableName = parts[parts.length - 1].replace(".json", "");
    return tableName;
  }

  /**
   * @param {*} mapName
   * @param {*} schema
   * @description 为指定地图在数据库中创建新的schema
   */
  async _addSchema(mapName, schema) {
    const currentVersion = this.db.verno;
    if (currentVersion >= 1) {
      // 修改schema前关闭数据库
      try {
        if (this.db.isOpen()) {
          await this.db.close();
        }
      } catch (e) {
        console.error(e);
      }

      // 收集现有表
      const existingSchema = this.db.tables.reduce((acc, table) => {
        acc[table.name] = table.schema.primKey.src;
        return acc;
      }, {});
      // 添加新表schema
      existingSchema[mapName] = schema;

      // 升级版本并更新schema
      await this.db.version(currentVersion + 1).stores(existingSchema);
      // 重新打开数据库
      await this.db.open();
    }
  }
}

问题现象

重启应用后,尝试通过db.converted_maps访问表时会提示该属性不存在,但查看db.storeNames数组和db._alltables对象,能明确看到converted_maps表的名称和相关信息。


内容的提问来源于stack exchange,提问作者lord_drgical

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 06:00:16