获取IndexedDB中已添加记录的键

qni6mghb  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(4)|浏览(149)

我在IndexedDB中有以下代码:

var request = objectStore.add({ entryType: entryType, entryDate: t});

现在,我想知道刚刚添加的记录的键。如何操作?
我找到了this article,以及以下代码:

var data = {"bookName" : "Name", "price" : 100, "rating":"good"};
var request = objectStore.add(data);
request.onsuccess = function(event){
    document.write("Saved with id ", event.result)
    var key = event.result;
};

这对我不起作用-键显示为未定义。我想我在这里缺少了一些基本的东西!

ngynwnxp

ngynwnxp1#

浏览此代码

var data = {"bookName" : "Name", "price" : 100, "rating":"good"};
var request = objectStore.add(data);
request.onsuccess = function(event){
    document.write("Saved with id ", event.result)
    var key = event.target.result;
};

希望这段代码可以检索最后插入的记录的关键字

kninwzqo

kninwzqo2#

The spec is written for user agent, not for developer. So it is confusing. Key generator is provided by the user agent.
Any event object that is received by onsuccess handler always have event.target.result . It is the key you are looking for. The key is auto generated if you don't provide it, assuming you set autoIncrement to true.
It is documented in Step 8: as follow:

  1. The result of this algorithm is key.
vlf7wbxs

vlf7wbxs3#

这里的诀窍是知道如何使用短语迭代搜索,直到你找到你需要的。我以前从未听说过IndexedDB,但似乎已经找到了你想要的。
我输入了"IndexedDB" into a search engine,发现了这个。这产生了短语“密钥生成器”,所以我输入了searched for that as well,这导致了this和这个。
StackOverflow链接讨论了如何使用UUID,当然UUID可以在JavaScript中生成,最后一个链接似乎有一些示例,可以实现您想要的功能。

agxfikkp

agxfikkp4#

如果您正在为IndexedDB使用idb Promise Package 器,那么新键就是add()调用的返回值:

import { openDB } from 'idb';

const db = await openDB(...);
const tx = db.transaction('mystore', 'readwrite');
const newId = await tx.store.add({ hello: 'world' });
await tx.done;

console.log(`Autogenerated unique key for new object is ${newId}`);

当然,请记住,只有在传递给createObjectStore()的选项中包含autoIncrement: true时,这才有效。

相关问题