我使用Emberjs适配器填充了indexedDB中的数据库。我已经设置了这样的密钥路径:
this.addModel(App.Device, { keyPath: 'key' });
当我第一次解析数据时,我的密钥会自动增加:
data = data.map(function( item, idx ) {
item.key = idx;
return item;
});
在所有数据都存储在indexedDB中之后,我想添加更多数据,但我需要继续在我的数据中设置一个键值。
如何获得最高密钥(在我的情况下,它是一个唯一的数字(如id)),所以我可以将当前数据中的密钥增加到我的数据库中?
以下是我想用来添加更多数据的代码示例:
var request = indexedDB.open( 'products' );
request.onsuccess = function( e ) {
console.log('Success!');
that.setProperties({ db: e.target.result });
var db = e.target.result;
var reader = new window.FileReader();
reader.readAsDataURL(blob_);
var img64;
reader.onloadend = function() {
base64data = reader.result;
var dataImage = {
key: 42,
url: url_,
base64: base64data
}
that.storage.saveProduct( db, dataImage );
}
};
request.onerror = function( e ) {
console.log('Error!');
console.dir( e );
};
[edit]我忘了把saveProduct fct:
this.saveProduct = function( db, data ) {
var transaction = db.transaction( ["App.Device"], "readwrite" );
var store = transaction.objectStore( "App.Device" );
var request = store.add( data );
request.onerror = function( e ) {
console.log("Error",e.target.error.name);
//some type of error handler
};
request.onsuccess = function( e ) {
console.log("Device saved in db");
};
};
答案 0 :(得分:2)
这是最后一个条目的IDB模式:
"0"
应该这样做,因为密钥按字典顺序排列。)(原始答案与问题https://stackoverflow.com/a/22812410/317937相关联,现已删除)prev
"或" prevunique
"方向,具体取决于您的需求)skip()
或continue()
应该有效)答案 1 :(得分:0)
将objectStore.openKeyCursor
用于“上一个”方向:
const openCursorRequest = store.openKeyCursor(null, 'prev')
openCursorRequest.onsuccess = () => {
const cursor = openCursorRequest.result
const maxKey = cursor && cursor.key
// use maxKey...
}
使用Promise
:
const getMaxKey = (db, storeName) => new Promise((resolve, reject) => {
const tx = db.transaction(storeName, 'readonly')
const store = tx.objectStore(storeName)
const openCursorRequest = store.openKeyCursor(null, 'prev')
openCursorRequest.onsuccess = () => {
const cursor = openCursorRequest.result
resolve(cursor && cursor.key)
}
openCursorRequest.onerror = () => {
reject(openCursorRequest.error)
}
})