在indexedDb中添加多个对象的正确方法?

Dev*_*ish 9 html javascript indexeddb

我有以下要添加到 indexedDb 的对象数组:

const data = [
    { name: 'abc',
      color: 'blue'
    },
    { name: 'xyz',
      color: 'red'
    },
    { name: 'yui',
      color: 'black'
    }];
Run Code Online (Sandbox Code Playgroud)

现在我创建数据库并将这些数据插入到存储中,如下所示:

if (!db.objectStoreNames.contains("people")) {
        peopleStore = db.createObjectStore("people", { keyPath: "name" });
        peopleStore.createIndex("color", "color", { unique: false });

        peopleStore.transaction.oncomplete = function(event) {
            data.forEach(function(data) {
                operations.add(data);
            });
        };
    }
Run Code Online (Sandbox Code Playgroud)

add()我已经使用(在 a 内)方法定义了一个函数表达式,const operations如下所示:

add: function(data) {
            let request = db
                .transaction(["people"], "readwrite")
                .objectStore("people")
                .add(data);
        }
Run Code Online (Sandbox Code Playgroud)

这是我的问题:

  1. 这种方式是在每次调用 add() 方法时创建一个新事务,还是将所有数据插入到单个事务中?

  2. 如果每次都创建一个新事务,我怎样才能只创建 1 个事务来提高性能并仅执行其中的所有操作。我猜我必须使用事务创建一个全局变量并对其执行操作(还有其他方法,例如edit()delete()等,其中每个方法都有一个“ request”变量在其中定义事务,类似于我已经在上面展示了)。我应该创建一个像这样的全局变量:

const globalTrans = db.transaction(["people"], "readwrite").objectStore("people");

  1. 创建新交易是一项成本高昂的操作吗?

预先感谢所有花时间回复的人!:)

Ujj*_*pta 9

创建全局变量会产生问题。可能某个事务正在运行,而对于另一个操作,您可能会覆盖它。

例如-

var globalTx;
// let's say you are selecting data from people
globalTx = db.transaction(["people"], "read")  // in read access
// and at same time you are inserting data from employee
globalTx = db.transaction(["employee"], "readwrite") // in read write
Run Code Online (Sandbox Code Playgroud)

解决问题的方法有很多种——

  1. 根据场景创建多种方法 -
// for single value
function add(data) {
    let request = db.transaction(["people"], "readwrite").objectStore("people").add(data);
}

// for multiple value
function addMultiple(datas, callback) {
    const tx = db.transaction(["people"], "readwrite");

    datas.forEach(data => {
        let request = tx.objectStore("people").add(data);
    })

    tx.oncomplete = function(event) {
        callback();
    }
};
Run Code Online (Sandbox Code Playgroud)
  1. 修改函数以仅接收数组值 -
// so now data will be only array    
function add(datas, callback) {
    const tx = db.transaction(["people"], "readwrite");

    datas.forEach(data => {
        let request = tx.objectStore("people").add(data);
    })

    tx.oncomplete = function(event) {
        callback();
    }
};

// so when want to insert single value , we will call like this.

const value = {
    id: 1,
    name: 'ujjwal'
}
add([value], () => {

})
Run Code Online (Sandbox Code Playgroud)

希望这能回答您的问题。