最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Indexeddb : How to limit number of objects returned? - Stack Overflow

programmeradmin2浏览0评论

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 ?

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 ?

Share Improve this question asked Aug 28, 2012 at 8:40 Philippe GirolamiPhilippe Girolami 1,8761 gold badge13 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11

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.

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.

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

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

You can set the start value, end value and if you should include the start and end value in the returned items. In my case i want the first value of the range, however i want to exclude the last value.

For details of IDBKeyRange please visit the W3C IndexedDB page

发布评论

评论列表(0)

  1. 暂无评论