indexeddb中多列的AutoIncrement

问题描述 投票:0回答:1

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

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

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

但无法找到我们如何为多列做同样的事情。据我所知 - 我们无法获得自动增量的价值。当我们插入数据时,该值将自动增加和添加。因此,如果我能以某种方式获得自动增量值,那么解决方案也是如此。

auto-increment indexeddb
1个回答
0
投票

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

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

例如:

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.