Suppose I have an IndexedDB collection with name items. All items have fields:

  • id
  • name
  • revision

revision field is a number field. I need to retrieve an item with max value of revision (or at least just retrive max revision value). What is the best way to do it?

share|improve this question
up vote 10 down vote accepted

First thing you need to do is create index on the revision field.

Then you need a search function which will use that index and open the index with inverse order of the objects. Then the first object will be the object you are looking for.

var index = objectStore.index('revision');
index.openCursor(null, 'prev'); 

The null states that you are searching for all values not a specific one, and the second parameter is the direction of the search.

Here is the sample code:

function getMaxNumber (callback) {
    var openReq = indexedDB.open(baseName);
    openReq.onsuccess = function() {
        var db = openReq.result;
        var transaction = db.transaction(objectStoreName, 'readonly');
        var objectStore = transaction.objectStore(objectStoreName);
        var index = objectStore.index('revision');
        var openCursorRequest = index.openCursor(null, 'prev');
        var maxRevisionObject = null;

        openCursorRequest.onsuccess = function (event) {
            if (event.target.result) {
                maxRevisionObject = event.target.result.value; //the object with max revision
            }
        };
        transaction.oncomplete = function (event) {
            db.close();
            if(callback) //you'll need a calback function to return to your code
                callback(maxRevisionObject);
        };
    }
}

Since the IndexedDB api is async you would need a callback function to return the value to your code.

share|improve this answer
    
Thanks a lot!!! I didn't think about to use direction of the cursor. Very cool! – alexpods Feb 20 '14 at 15:43
    
One more question: why not just call callback in openCursorRequest.onsuccess listener? Is it important to call it after db.close() ? – alexpods Feb 21 '14 at 8:18
1  
No Alex, this is just the way I use the API, since most of the time I iterate through multiple values with the 'onsuccess' event and return the values in the 'oncomplete' event. In your case it would be faster to return the value within the 'onsuccess' event. – Deni Spasovski Feb 21 '14 at 14:02
    
I never close the db, there is a dbPromise in the module I wrote that when resolved returns the db but it is only set once when the module is loaded. So after getting the value I do: cursor && cursor.advance(1000000); this casses onsuccess function to be called once more but e.target.result is null. – HMR Oct 27 '16 at 8:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.