Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexeddb : How to limit number of objects returned?

I'm using a cursor with a lower bound range query. I can't find a way to limit the number of objects returned, similar to a "LIMIT n" clause in a databse.

var keyRange = IDBKeyRange.lowerBound('');

Does it not exist ?

like image 665
Philippe Girolami Avatar asked Aug 28 '12 08:08

Philippe Girolami


2 Answers

As you're iterating through the results, you can stop at any time. Something like this should work:

var results = [];
var limit = 20;
var i = 0;

objectStore.openCursor().onsuccess = function (event) {
  var cursor = event.target.result;
  if (cursor && i < limit) {
    results.push(cursor.value);
    i += 1;
    cursor.continue();
  }
  else {
    // Do something with results, which has at most 20 entries
    console.log(results);
  }
};

Also, in the special case where you are selecting based on a key that is made up of sequential numbers, you could use a keyRange to explicitly return only a certain range. But that's generally not the case.

like image 172
dumbmatter Avatar answered Nov 13 '22 18:11

dumbmatter


An important fix its replace:

if (cursor && i < limit) {

for

if (cursor && results.length < limit) {

Remember that its an async call, and it could be adding elements on "results" at the same time and "i" would not have the proper value.

like image 29
Hans Langer Avatar answered Nov 13 '22 16:11

Hans Langer