IndexedDB在向数据库中添加新值时引发错误

xfyts7mz  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(3)|浏览(503)

我在IndexedDb中成功创建了一个数据库,但当我尝试向数据库中添加值时,我看到以下错误:
DOM例外:无法在“IDBObjectStore”上执行“添加”:评估对象存放区的索引键路径未产生值。
程式码片段:

let db = new AngularIndexedDB('myDb', 1);

db.createStore(1, (evt) => {
  const objectStore = evt.currentTarget.result.createObjectStore('people', { keyPath: 'id', unique: true });
    objectStore.createIndex("name", "name", { unique: false });
    objectStore.createIndex("email", "email", { unique: true });
  }).then(() => {
    db.add('people', { name: 'name', email: 'email' }).then(() => {
  }, (error) => {
    console.log(error);
  });

}, (error) => {
   console.log(error);
});

我检查了表的名称。这是完全相同的。以及它的值各自的键。
如何解决此问题?您能否分享一下对此错误的见解?
您的帮助将不胜感激。提前感谢。

kadbb459

kadbb4591#

使用密钥路径创建对象存储时:

const store = db.createObjectStore('people', { keyPath: 'id' });

然后:
1.您还必须指定存储区应使用密钥生成器,例如{keyPath: 'id', autoIncrement: true},这将导致为您生成数字密钥(1、2、3...)并将其注入到值中;或:
1.您存储的值必须已经包含与keypath匹配的属性,例如store.put({name: 'foo', id: 1234})
(Also,unique不是对象存放区的属性,只有索引。索引键在对象存放区内永远是唯一的。)

u59ebvdq

u59ebvdq2#

在我的例子中,当我试图强制IndexDB在数据库中创建一个记录的副本时,我遇到了这个错误,方法是保存一个记录的深层副本,其中的键被分配了一个'undefined'。

const record: T = JSON.parse(JSON.stringify(r));
 r.key = undefined; // does not work!
 delete(r.key); // works! with autoincrement it forces IndexDB to create a new key
 await datastore.add(record);
xqk2d5yq

xqk2d5yq3#

对于那些面临类似问题的TypeScript属性。
假设我们有这个模型

export default class Model {
   private _id: number;
   public get id(){
      return this._id;
   }
   public set id(value: number){
      this._id = value;
   }
}

我们这样初始化objectStore

db.createObjectStore('Models', {
                        keyPath: 'id'
                    });

然后我们要保存模型

let model = new Model();
   let ts = db.transaction('Models', "readwrite");
   let store = ts.objectStore('Models');
   store.add(model);

很遗憾,我们将收到

DOMException: Failed to execute 'add' on 'IDBObjectStore': Evaluating the object store's key path did not yield a value.

这是因为现在IndexedDB在解释我们的transpiled模型时有问题(我不知道为什么,它可能与tsconfig.json有关吗?)
一旦我们将模型改为

export default class Model {
      public id: number;
   }

然后尝试保存它,我们将实现一个成功完成的事务。

相关问题