IDB:openCursor() 不是函数

IDB: openCursor() is not a function

好吧,也许我做错了什么......但是这个错误非常令人困惑。我坚持:"Uncaught TypeError: requestChatHistory.openCursor is not a function at IDBOpenDBRequest.dbPromise.onsuccess"

IDBOpenRequest 可能继承 IDBRequest 的方法...

我尝试在没有 openCursor() 的情况下发出请求并从中获取第一个值。 还尝试重新创建数据库,使用不同的浏览器(Chrome、Edge、Firefox)

onUpgrade承诺:

dbPromise.onupgradeneeded = function(event) { 
        let db = event.target.result;
        db.createObjectStore('keys', {keyPath: 'userId'});
        let chatHistory = db.createObjectStore('messages', { keyPath: "id", autoIncrement:true });
        chatHistory.createIndex("chatId", "chatId", { unique: false });
    };

有我的功能要求:

async function loadSavedMessages(chatId){
        let dbPromise = idb.open('clientDB', 3);
        dbPromise.onsuccess = function() {
            let db = this.result;
            let dbTransaction = db.transaction(["messages"]);
            let messages = dbTransaction.objectStore("messages");
            let index = messages.index('chatId'); 
            let requestChatHistory = index.get(chatId);
            requestChatHistory.openCursor().onsuccess = function(event) {
                let cursor = event.target.result;
                if (cursor) {
                    console.log(cursor);
                    cursor.continue();
                }
            };
        }
    }

保存数据的函数:

async function saveMessage(chatId, message, userId){
        let dbPromise = idb.open('clientDB', 3);
        dbPromise.onsuccess = function() {
            let db = this.result;
            let dbTransaction = db.transaction(["messages"], 'readwrite');
            let messages = dbTransaction.objectStore("messages");
            let mesObj = {
                chatId: chatId,
                user: userId,
                message: message,
                timestamp: Date.now()
            };
            let save = messages.add(mesObj);
            save.onerror = function(event) {
                // Handle errors!
                console.log("Something went wrong with local DB :(")
            };
            save.onsuccess = function(event) {
                // Do something with the request.result!
                console.log(`Message saved, id ${save.result}`);
            };
        }
    }

这是你的问题:

            let requestChatHistory = index.get(chatId);
            requestChatHistory.openCursor().onsuccess = function(event) {

requestChatHistory 是一个 IDBRequest, which has no openCursor method. openCursor is on IDBIndex,就像您的 index 变量一样。所以也许你打算做这样的事情:

            index.openCursor(chatId).onsuccess = function(event) {