对indexedDB查询的结果进行排序

viv*_*k.m 10 javascript indexeddb

我想对从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();
  };
Run Code Online (Sandbox Code Playgroud)

Kya*_*Tun 18

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

var cursorRequest = store.index('date').openCursor(null, 'next'); // or prev 
Run Code Online (Sandbox Code Playgroud)

这将获得排序结果.这就是应该如何使用索引.


And*_*aru 8

这是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....
    }
};
Run Code Online (Sandbox Code Playgroud)

有关光标方向的更多信息,请访问:http://www.w3.org/TR/IndexedDB/#cursor-concept

IDBIndex API位于:http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex


viv*_*k.m -3

感谢 zomg、hughfdjackson 的 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();
};
Run Code Online (Sandbox Code Playgroud)

  • 这种做法忽略了使用indexedDB 的全部意义。您可能希望使用indexedDB“索引”按非主键属性进行排序。然后,您可以在索引上打开游标并以四种方式之一进行迭代(next、prev、nextUnique、prevUnique)。您选择的非本地排序并不是最佳选择。 (14认同)