2012-07-15 15 views
6

indexedDBから取得した結果を並べ替える必要があります。
各レコードは構造体{id、text、date}を持ち、 'id'はkeyPathです。indexedDBクエリの結果を並べ替える

結果を日付で並べ替える必要があります。

私の現在のコードは以下の通りです:

var trans = db.transaction(['msgs'], IDBTransaction.READ); 
    var store = trans.objectStore('msgs'); 

    // Get everything in the store; 
    var keyRange = IDBKeyRange.lowerBound(""); 
    var cursorRequest = store.openCursor(keyRange); 

    cursorRequest.onsuccess = function(e) { 
    var result = e.target.result; 
    if(!!result == false){ 
     return; 
    } 
    console.log(result.value); 
    result.continue(); 
    }; 
+0

-Whereは、あなたのSQLクエリです - 申し訳ありません? 、私のせい - 私はWebSQLを考えました! – Oliver

+0

参照http://stackoverflow.com/questions/12084177/in-indexeddb-is-there-a-way-to-make-a-sorted-compound-query/15625231#15625231 要するに、キーの配列インデックスとして。 – 173210

答えて

-4

JavaScriptのIRCのZOMG、hughfdjacksonのおかげで、私は、最終的な配列をソート。以下のように変更されたコード:

var trans = db.transaction(['msgs'], IDBTransaction.READ); 
var store = trans.objectStore('msgs'); 

// Get everything in the store; 
var keyRange = IDBKeyRange.lowerBound(""); 
var cursorRequest = store.openCursor(keyRange); 

var res = new Array(); 

cursorRequest.onsuccess = function(e) { 
    var result = e.target.result; 
    if(!!result == false){ 
     **res.sort(function(a,b){return Number(a.date) - Number(b.date);});** 
     //print res etc.... 
     return; 
    } 
    res.push(result.value); 
    result.continue(); 
}; 
+7

この種のものは、indexedDBを使用する際に欠けています。 indexedDB 'index'を使用して、プライマリ以外のキーのプロパティでソートしたいとします。次に、インデックスにカーソルをあて、4つの方法(next、prev、nextUnique、prevUnique)のいずれかで繰り返します。非ネイティブでソートするのは最適ではありません。 – Josh

+0

それは理にかなっています。ありがとう!次回にindexedDBを使用するときは、そのことを覚えておきます。 –

+2

この回答は最も正しいものではありません。 – buley

14

実際にあなたがmsgs ObjectStoreの中でインデックスにdateフィールドを持っており、ObjectStoreの上のインデックスカーソルをオープン。

var cursorRequest = store.index('date').openCursor(null, 'next'); // or prev 

これでソート結果が得られます。これが索引の使用方法です。

6

Joshが提案したより効率的な方法があります。ここにカーソル方向に

// Use the literal "readonly" instead of IDBTransaction.READ, which is deprecated: 
var trans = db.transaction(['msgs'], "readonly"); 
var store = trans.objectStore('msgs'); 
var index = store.index('date'); 

// Get everything in the store: 
var cursorRequest = index.openCursor(); 
// It's the same as: 
// var cursorRequest = index.openCursor(null, "next"); 
// Or, if you want a "descendent ordering": 
// var cursorRequest = index.openCursor(null, "prev"); 
// Note that there's no need to define a key range if you want all the objects 

var res = new Array(); 

cursorRequest.onsuccess = function(e) { 

    var cursor = e.target.result; 
    if (cursor) { 
     res.push(cursor.value); 
     cursor.continue(); 
    } 
    else { 
     //print res etc.... 
    } 
}; 

詳細:あなたが "日付" にインデックス作成されたと仮定すると

http://www.w3.org/TR/IndexedDB/#cursor-concept

IDBIndex APIはここにある:http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex

関連する問題