15

I want to sort results obtained from indexedDB.
Each record has structure {id, text, date} where 'id' is the keyPath.

I want to sort the results by date.

My current code is as below:

  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();
  };
4

3 回答 3

24

实际上,您必须在 objectStore 中索引date字段并在msgsobjectStore 上打开索引游标。

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

这将得到排序的结果。这就是应该使用索引的方式。

于 2012-10-04T07:44:05.243 回答
10

这是 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

于 2014-07-31T09:14:10.397 回答
-3

感谢 zomg,hughfdjackson of javascript irc,我对最终数组进行了排序。修改后的代码如下:

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();
};
于 2012-07-15T13:22:27.987 回答