在给定索引的情况下,如何读取indexeddb自动增量对象库中的对象键 [英] How do I read an objects key in an indexeddb autoincrement objectstore, given an index
问题描述
这个代码形式的问题,我可以用 .put(doc,key)
来覆盖对象,但我无法弄清楚如何读取它的密钥
This question in code form, I can use .put(doc, key)
to overwrite the object, but I cant figure out how to read its key
// After writing doc1 to an autoincrement
// objectStore, I want to overwrite it
// later, I only know its index
// (not its key)
var docs = [
{'a':'doc1', 'my_index': 'anindex'},
{'a':'doc2', 'my_index': 'anindex'}
];
indexedDB.deleteDatabase('foo').onsuccess = function () {
var idb;
var req = indexedDB.open('foo');
function writeDocs(docs) {
if (!docs.length) {
console.log('done writing');
return;
}
var txn = idb.transaction(['some_store_name'], 'readwrite');
var doc = docs.shift();
console.log('writing', doc);
var get = txn.objectStore('some_store_name').index('my_index')
.get(doc.my_index);
get.onsuccess = function(e) {
var key = null;
if (e.target.result) {
// If there is a result here, I want to overwrite it
// to do that I need its key, cant find it here?
console.log(e.target.result);
}
var dataReq = txn.objectStore('some_store_name').put(doc);
dataReq.onsuccess = function (e) {
console.log('wroted', e.target.result);
writeDocs(docs);
}
dataReq.onerror = function () {
console.log('it broke');
writeDocs(txn, docs);
}
}
};
req.onupgradeneeded = function(e) {
var db = e.target.result;
db.createObjectStore('some_store_name', {autoIncrement : true})
.createIndex('my_index', 'my_index', {unique: true});
};
req.onsuccess = function(e) {
idb = e.target.result;
writeDocs(docs);
};
}
推荐答案
if (e.target.result) {
// If there is a result here, I want to overwrite it
// to do that I need its key, cant find it here?
console.log(e.target.result);
}
e.target.result
其实是关键!但仅作为对的回复
或添加
,而不是获取
。您可以将此值用于 put()
将来的数据。
e.target.result
is in fact the key! But only as a response to put
or add
, not a get
. You can use this value to put()
the data in the future.
使用外线键,例如你有: objectstore.put(数据,密钥)
With out of line keys, like you have: objectstore.put(data, key)
使用内联键,你只需 objectstore.put(data)
更新:问题是你在循环 writeDocs
但是在你的第一个循环中 key
是 null
所以它会抛出一个错误。
Update: The problem is you're looping writeDocs
but in your first loop key
is null
so it throws an error.
第二次更新:看起来某些代码可能已添加,或者我之前遗漏了一些内容。除了我上面标记的内容,但您的索引是 unique
,并且您使用相同的 my_index
值两次因此第二个 put()
的错误。我通过在每个页面加载中使 my_index
唯一来避免这个问题。
Second Update: It looks like some code may have been added, or I missed something earlier. In addition to what I have flagged above, but your index is unique
and you're using the same my_index
value twice, hence the error on second put()
. I avoided this problem in my fiddle solution by making my_index
unique each pageload.
这篇关于在给定索引的情况下,如何读取indexeddb自动增量对象库中的对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!