我正在创建一个indexeddb,并且其中有几个存储。 创建商店时必须首先添加一些数据。
我有创建数据库和存储的功能:
function db_init(){
var request = indexedDB.open("db", "1.0");
request.onupgradeneeded = function(){
var db = request.result;
//store 1
db.createObjectStore("store1", {keypath: "id", autoIncrement: true});
//add initial datas;
//store2
db.createObjectStore("store2", {keypath: "id", autoIncrement: true});
//...
//store 3
// init necessary databases
db_populate();
}
request.onsuccess = function (){
db = request.result;
populate:db();
}
}
在 db_populate 函数内部还有 4 个其他函数,我可以在其中填充数据存储:
function db_populate() {
init_store1();
init_store2();
//...
console.log("db populated with data");
}
每个 init_score 都会使用如下所示的交易填充商店:
var tx = db.transaction("store1", "readwrite");
var store = tx.objectStore("store1");
现在,我遇到了一个问题。每次打开或刷新页面时,初始数据都会重复。还有再补充过来。
当我在 onupgradeneeded
函数末尾添加 db_populate 时,出现错误:
Uncaught TypeError: Cannot read property 'transaction' of undefined
上线:
var tx = db.transaction ("store1", "readwrite");
我想要实现的目标是使用其初始数据创建数据存储一次,仅此而已。
知道我做错了什么吗?
提前致谢。
最佳答案
这是因为您无法在需要升级的事件期间插入数据。您需要做的是在升级后关闭连接并再次重新打开连接以进行数据插入。
流程应该是这样的:
function db_init() {
var request = indexedDB.open("db");
var dbShouldInit = false;
request.onupgradeneeded = function(e) {
var db = e.target.result;
dbShouldInit = true;
//store 1
db.createObjectStore("store1", {
keypath: "id",
autoIncrement: true
});
//add initial datas;
//store2
db.createObjectStore("store2", {
keypath: "id",
autoIncrement: true
});
}
request.onsuccess = function(e) {
e.target.result.close();
if(dbShouldInit)//executes only if DB init happened
db_populate(); //close the db first and then call init
}
}
function db_populate() {
init_store1(init_store2); //pass init 2 as callback
}
function init_store1(callback) {
var request = indexedDB.open("db");
request.onsuccess = function(e) {
var db = e.target.result;
var tx = db.transaction("store1", "readwrite");
var store = tx.objectStore("store1");
//init code here
tx.oncomplete = function(e) {
callback(); //here call the init for second function
};
}
}
function init_store2() {
var request = indexedDB.open("db");
request.onsuccess = function(e) {
var db = e.target.result;
var tx = db.transaction("store2", "readwrite");
var store = tx.objectStore("store2");
//init code here
tx.oncomplete = function(e) {
//here the app can continue
};
}
}
关于javascript - 如何在indexeddb中仅添加一次初始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27359748/