Indexeddb: How to limit the number of returned objects?

I am using a cursor asking for a range of lower bounds. I cannot find a way to limit the number of returned objects, similar to the "LIMIT n" clause in the database.

var keyRange = IDBKeyRange.lowerBound(''); 

Does he not exist?

+6
source share
3 answers

As you iterate over 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); } }; 

In addition, in the special case, when you select based on a key consisting of consecutive numbers, you can use keyRange to explicitly return only a certain range. But this is not so at all.

+6
source

An important fix replaces:

 if (cursor && i < limit) { 

for

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

Remember that this is an asynchronous call, and it can add elements to the β€œresults” at the same time, and β€œi” will not have the correct value.

+2
source

You can even search by range in indexedDB using the IDBKeyRange.bound function

 IDBKeyRange.bound(keyValueFrom, keyValueTo, false, true); 

You can set the start value, the end value, and if you must specify the start and end value in the returned elements. In my case, I want the first value of the range, however I want to exclude the last value.

For more on IDBKeyRange, please visit the W3C IndexedDB page .

0
source

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


All Articles