添加对象
IndexedDB 数据库中的数据需要发生的任何事情都发生在事务中。关于本页底部的备注部分中提到的事务,有几点需要注意。
我们将使用我们在打开数据库中设置的数据库。
// Create a new readwrite (since we want to change things) transaction for the things store
var transaction = db.transaction(["things"], "readwrite");
// Transactions use events, just like database open requests. Let's listen for success
transaction.oncomplete = function() {
console.log("All done!");
};
// And make sure we handle errors
transaction.onerror = function() {
console.log("Something went wrong with our transaction: ", transaction.error);
};
// Now that our event handlers are set up, let's get our things store and add some objects!
var store = transaction.objectStore("things");
// Transactions can do a few things at a time. Let's start with a simple insertion
var request = store.add({
// "things" uses auto-incrementing keys, so we don't need one, but we can set it anyway
key: "coffee_cup",
name: "Coffee Cup",
contents: ["coffee", "cream"]
});
// Let's listen so we can see if everything went well
request.onsuccess = function(event) {
// Done! Here, `request.result` will be the object's key, "coffee_cup"
};
// We can also add a bunch of things from an array. We'll use auto-generated keys
var thingsToAdd = [{ name: "Example object" }, { value: "I don't have a name" }];
// Let's use more compact code this time and ignore the results of our insertions
thingsToAdd.forEach(e => store.add(e));