2017-06-05 11 views
1

私は現在オブジェクトストアのキーパスとして​​を使用しています。IndexedDbで日付をインデックスとして使用し、それを使ってソートする

私は最新のエントリを取得するために使用できるインデックス - createdを追加したいと思います。

const latestMediaRequest = store.getAll(); 
latestMediaRequest.onsuccess = function (event) { 
     const allData = event.target.result; 
     const targetEntry = allData[allData.length - 1]; // nope    
} 

これは私が現在だ方法です: enter image description here

これは、私はもともと(getNewest経由)最新のエントリを取得しようとしたが、それは期待通りに働いていなかった方法です:私は、インデックスを追加しましたエントリの追加(作業):

const request = database.transaction(storeName, "readwrite") 
       .objectStore(storeName) 
       .add(dbEntry); // contains "created" timestamp 

そして、私はGUIDで取得していますどのようにこれがある(作業):

const request = database.transaction(storeName, "readwrite") 
       .objectStore(storeName) 
       .get(mediaId); 

私はここで、インデックスを作成しました:

  request.onupgradeneeded = function (event) { 
       const db = event.target.result; 
       if (db.objectStoreNames.contains(storeName)) { 
        db.deleteObjectStore(storeName); 
       } 
       const objectStore = db.createObjectStore(storeName, { keyPath: keyPath }); 
       objectStore.createIndex("created", "created", { unique: false }); 
      }; 

はどのようにgetNewestスニペットは、日付インデックスの順序によってフェッチをサポートするように変更することができますか?これを使用して最も古いアイテムを再帰的に削除するので、ただ1つの "lastAdded"エントリを保存することはできません。

答えて

0

これはトリックでした:

// "created" 
const latestMediaRequest = store.index(dateIndex).openCursor(); 
latestMediaRequest.onsuccess = function (event) { 
    const targetEntry = event.target.result.value; 
} 
+2

'openCursor(ヌル、 '前へ')'最後の日から開始すると – Josh

関連する問題