如何在 indexedDB 中存储 mongodb 集合数组

how to store a mongodb array of collections inside an indexedDB

您好,我想为我的 phonegap 建立一个本地数据库,以便用户可以离线使用它。

我在 angular 创建数据库的函数中有这个。

   function Database() {

    return {
        create: function (itemDocs) {

            var db = null;

            var request = indexedDB.open("myDB", 1);

            request.onsuccess = function (event) {
                db = event.target.result;
                console.log("DB loaded successfully");

            };

            request.onerror = function (event) {
                console.log(event)
            };

            request.onupgradeneeded = function (event) {
                db = event.target.result;
                console.log("DB initiliazed / created");

                //create collections
                db.createObjectStore("items", {keyPath: "_id"});

                //create documents
                var transaction = db.transaction(["items"], "readwrite");

                var items = transaction.objectStore("items");

                items.add(itemDocs);

            };


        }
    }

}

itemDocs 包含一个 mongoDB 集合(这是一个对象数组),我想将该集合存储在 indexedDB 数据库中,我遇到的问题是我遇到了这个恼人的错误。

Uncaught InvalidStateError: Failed to execute 'transaction' on 'IDBDatabase': A version change transaction is running.

使用var transaction = event.target.transaction代替var transaction = db.transaction(...);

完整的答案相当冗长。简而言之,您不想在 onupgradeneeded 中创建新事务。已经有一个有效的交易可供您使用。