2012-07-15 49 views
6

我想對從索引數據庫獲得的結果進行排序。
每條記錄​​都有結構{id,text,date},其中'id'是keyPath。排序索引數據庫查詢的結果

我想按日期排序結果。

我當前的代碼是如下:

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 2012-07-15 12:54:28

+0

請參閱http://stackoverflow.com/questions/12084177/in-indexeddb-is-there-a-way-to-make-a-sorted-compound-query/15625231#15625231 總之,使用一組鍵作爲索引。 – 173210 2016-03-27 02:15:24

回答

-4

由於ZOMG,JavaScript的IRC的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的全部觀點。你會想使用索引數據庫的'索引'按非主鍵屬性進行排序。然後你可以在索引上打開一個遊標並以四種方式之一進行迭代(next,prev,nextUnique,prevUnique)。您選擇非本地排序並非最佳選擇。 – Josh 2013-04-15 18:41:41

+0

這很有道理。謝謝!下次我使用indexedDB時,我會記住這一點。 – 2013-06-20 03:52:01

+2

這個答案不是最正確的答案。 – buley 2014-03-12 13:25:21

14

其實你不得不指數在msgs對象存儲的date領域開放對對象存儲的指標光標。

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