Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexedDB: Retrieve item with max value

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?

like image 628
alexpods Avatar asked Feb 20 '14 13:02

alexpods


1 Answers

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.

like image 106
Deni Spasovski Avatar answered Sep 25 '22 18:09

Deni Spasovski