Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...