如何获取时间戳值最高的x个对象

How to obtain x objects with highest timestamp value?

本文关键字:对象 时间戳 何获取 获取      更新时间:2023-09-26

我是web应用程序开发的新手,找不到以下问题的解决方案。基本上,我试图从IndexedDB数据库中对最新对象的数组进行排序。每个对象都包含一个时间戳值。我已经在时间戳上创建了一个索引,我能够获得具有最高值的对象。

    function getMails (numberOfMessages, _function) {
/*  This function uses asynchronous methods, hence you have to pass the key and function that will receive
    the messageitem as a parametr */
    if (typeof optionalArg === 'undefined') {
     optionalArg = 10;
    }
    function _getMails (db) {
        var transaction = db.transaction(["MessageItem"], "readonly");
        var store = transaction.objectStore("MessageItem");
        var index = store.index("timestamp");
        var cursor = index.openCursor(null, 'prev');
        var maxTimestampObject = null;
        cursor.onsuccess = function(e) {
            if (e.target.result) {
                maxTimestampObject = e.target.result.value;
                _function(maxTimestampObject);
            }
        };
    }
    openDB(_getMails);
}

函数openDB打开数据库,并将db对象作为参数传递给_getMails函数。函数getMails当前只传递时间戳值最高的对象。我可以迭代数据库x(numberOfMessages)次,并始终选择时间戳最高的对象,同时排除我试图获取的数组中已经存在的对象。但我不确定这是否是最方便的方式。谢谢你的回复。一月

您只需要在onsuccess函数中调用cursor.continue()。它将与下一个光标结果一起被再次调用。

谢谢Kyaw Tun。这是我为那些感兴趣的人准备的最后一个代码:

function openDB(_function) {
// Opening the DB
var openRequest = indexedDB.open("TsunamiDB",1);
openRequest.onupgradeneeded = function(e) {
    console.log("Upgrading...");
    var thisDB = e.target.result;
    if (!thisDB.objectStoreNames.contains("MessageItem")) {
        var objectStore = thisDB.createObjectStore("MessageItem");
        objectStore.createIndex("timestamp", "envelope.timestamp", {unique:false});
    }
}
openRequest.onsuccess = function(e) {
    console.log("Success!");
    _function(e.target.result);
}
openRequest.onerror = function(e) {
    console.log("Error");
    console.dir(e);
}}

此函数使用异步方法,因此您必须传递将作为参数接收messageitem的键和函数。Paremetr是x(numberOfMessages)最新消息的数组。对数组进行排序,以便索引为0的消息是最新的消息。

function getMails ( _function, numberOfMessages) {
if (typeof numberOfMessages === 'undefined') {
 numberOfMessages = 10;
}
function _getMails (db) {
    var transaction = db.transaction(["MessageItem"], "readonly");
    var store = transaction.objectStore("MessageItem");
    var index = store.index("timestamp");
    var objectsArray = [];
    var i = 0;
    index.openCursor(null, 'prev').onsuccess = function(e) {
        var cursor = e.target.result;
        if (cursor && i < numberOfMessages) {
            objectsArray.push(cursor.value)
            ++i;
            cursor.continue();
        }
    };
    transaction.oncomplete = function(e) {
        _function(objectsArray);
    }
}
openDB(_getMails);}