IndexedDB:检索具有最大值的项目 [英] IndexedDB: Retrieve item with max value

查看:229
本文介绍了IndexedDB:检索具有最大值的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 items IndexedDB 集合。所有项目都有字段:

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


  • id

  • name

  • 修订

修订版字段是一个数字字段。我需要检索具有最大修订值的项目(或者至少只检索最大修订版本值)。最好的方法是什么?

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?

推荐答案

首先要做的是在 revision field。

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'); 

null表示您搜索的所有值都不是特定的值,第二个参数是搜索方向。

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

以下为示例代码:

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);
        };
    }
}

由于 IndexedDB api是异步的,你需要一个回调函数来将值返回给你的代码。

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

这篇关于IndexedDB:检索具有最大值的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆