首页 > 解决方案 > 在不知道架构的情况下简单地写入 Dexie

问题描述

是否可以在不知道架构的情况下将整个对象写入 Dexie?我只想这样做:

var db = new Dexie(gameDataLocalStorageName);
                db.version(1).stores({
                    myData: "gameData"
                });
                db.myData.put(gameData);
                console.log(db.myData.get('gameData'));

但我收到以下错误:

Unhandled rejection: DataError: Failed to execute 'put' on 'IDBObjectStore': Evaluating the object store's key path did not yield a value.
 DataError: Failed to execute 'put' on 'IDBObjectStore': Evaluating the object store's key path did not yield a value.

标签: dexie

解决方案


错误是因为您已指定架构以使用入站键“gameData”,即要求每个对象都将属性“gameData”作为其主键。

如果您不需要在对象中拥有主键,则可以将架构声明为{myData: ""}而不是{myData: "gameData"}. 通过这样做,您将需要在对 的调用中提供与对象分开的主键db.myData.put()

请参阅文档以了解入站与非入站键详细的架构语法

var db = new Dexie(gameDataLocalStorageName);
db.version(1).stores({
  myData: ""
});
Promise.resolve().then(async () => {
  await db.myData.put(gameData, 'gameData'); // 'gameData' is key.
  console.log(await db.myData.get('gameData'));
}).catch(console.error);

由于我们在这里更改了主键,因此您需要先在 devtools 中删除数据库,然后才能使用。


推荐阅读