对indexedDB查询的结果进行排序

Sorting the results of an indexedDB query

本文关键字:排序 结果 indexedDB 查询      更新时间:2023-09-26

我想对从indexedDB获得的结果进行排序
每条记录都有结构{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();
  };

实际上,您必须对msgs objectStore中的date字段进行索引,并在objectStore上打开索引光标。

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

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

以下是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-概念

IDBIndex API在这里:http://www.w3.org/TR/IndexedDB/#idl-def IDBIndex

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

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