0

My question is similar to this question, except I want to do this on an index with multiple fields, where one of the fields has a particular value.

So, for example, I have a store named ExerciseSets. ExerciseSets has an index made up of two fields, exerciseId and performedDate. I would like to query the most recent row (as determined by performedDate) with an exerciseId of 1.

Community
  • 1
  • 1
w.brian
  • 16,296
  • 14
  • 69
  • 118

1 Answers1

1

And the answer is really similar, you need to create a compound index and then retrieve the data from that index in reverse order. In this example I'm using time stamps for storing the Date.

First you need to create the compound index during onupgradeneeded event:

store.createIndex('nametimestamp', ['text', 'timeStamp']);
//text and timestamp are my field names

And then use it for your search function:

searchIndexedDB = function (value, callback) {
  var request = indexedDB.open(dbName);
  request.onsuccess = function(e) {
    var db = e.target.result;
    var trans = db.transaction(objectStoreName, 'readonly');
    var store = trans.objectStore(objectStoreName);
    var index = store.index('nametimestamp');
    var keyRange = IDBKeyRange.bound([value,0], [value, new Date().getTime()]);
    //open the index for all dates and for only one value
    var openCursorRequest = index.openCursor(keyRange, 'prev');
    //open the database sorted by time stamp - descending 

    openCursorRequest.onsuccess = function(e) {
        if(e.target.result)
            callback(e.target.result.value);
    };

    trans.oncomplete = function(e) {
        db.close();
    };

    openCursorRequest.onerror = function(e) {
        console.log("Error Getting: ", e);
    };
  };
  request.onerror = myStorage.indexedDB.onerror;
}
Community
  • 1
  • 1
Deni Spasovski
  • 4,004
  • 3
  • 35
  • 52