在不了解模式的情况下简单地写信给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.

错误是因为您指定了使用入站密钥的模式"gameData";,即要求每个对象具有属性"0";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中删除数据库,然后才能工作。

最新更新