Sorting query results indexedDB

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

I want to sort the results by date.

My current code is as follows:

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(); }; 
+6
source share
3 answers

Thanks to zomg, hughfdjackson from javascript irc, I sorted the last array. Modified code as shown 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); 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(); }; 
-4
source

In fact, you need to index the date field in the msgs objectStore and open the pointer cursor on the Store.

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

This will give a sorted result. This is how indexes should be used.

+14
source

Here's a more efficient way suggested by Josh.

Suppose you created an index on a "date":

 // 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 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 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.... } }; 

More information about the direction of the cursor here: http://www.w3.org/TR/IndexedDB/#cursor-concept

The IDBIndex API is here: http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex

+7
source

Source: https://habr.com/ru/post/920518/


All Articles