【问题标题】:AutoIncrement of Multiple columns in indexeddbindexeddb中多列的自动增量
【发布时间】:2019-04-06 18:56:15
【问题描述】:

有谁知道 - 我们如何为 indexeddb 中的两列指定自动增量。

我知道 - 我们可以在创建这样的表时为一列指定自动增量 -

var objectStore = thisDb.createObjectStore("note", { keyPath: "id", autoIncrement:true });

但无法找到如何对多个列执行相同操作。据我所知 - 我们无法获得自动增量的值。当我们插入数据时,该值将自动递增和添加。所以如果我能以某种方式获得自动增量值,那也是解决方案。

【问题讨论】:

    标签: auto-increment indexeddb


    【解决方案1】:

    您不能在商店中创建两个自动递增的属性。该功能仅适用于定义为键路径的属性。

    您可以轻松获得自动递增的值。该值作为插入新对象的putadd 请求的result 提供。

    例如:

    function addThing(db, thing) {
      return new Promise((resolve, reject) => {
        let id = undefined;
    
        const transaction = db.transaction('things', 'readwrite');
        const store = transaction.objectStore('things');
    
        // wait to resolve the promise until the transaction is completed
        // so that we do not prematurely pretend the operation succeeded. resolve 
        // to the value of the new id
        transaction.oncomplete = event => resolve(id);
    
        transaction.onerror = event => reject(event.target.error);
    
        // store.add also works here
        const request = store.put(thing);
    
        // listen for the add event and grab the value of the new id
        // that indexedDB generated and store it in the id variable
        request.onsuccess = event => id = event.target.result;
      });
    }
    
    
    async function doSomething() {
      const something = {bar: 'baz'};
    
      const db = await open(...);
      const id = await addThing(db, something);
      db.close();
    
      something.id = id;
      console.log(something);
    }
    

    【讨论】:

    • 好的,谢谢乔希。我们可以在执行任何操作之前获取自动增量值 - 添加、放置等。这样我就可以将自动增量值用于需要自动增量的其他列?
    • 很确定获得此值的唯一方法是发出 put/add 请求。
    • 正确,在请求成功之前生成的密钥不可用。原因是在那之前这个数字是未知的。您可以针对同一个存储调用 db.transaction() 两次并开始针对两者发出 put(),尽管来自第二个事务的请求甚至在第一个事务完成之前都不会开始运行。因此,为这些请求生成的密钥完全取决于第一个事务发生的情况(可能成功、中止等)。您可以自己实现一个,而不是依赖内置的密钥生成器机制。
    猜你喜欢
    • 2011-11-13
    • 1970-01-01
    • 2016-08-19
    • 2011-10-28
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2021-02-17
    相关资源
    最近更新 更多