Web | indexedDB的常见错误总结

关于transaction的错误

代码
let db;
window.onload = function() {
// Open our database; it is created if it doesn't already exist
// (see onupgradeneeded below)
let request = window.indexedDB.open('notes', 1);
// onerror handler signifies that the database didn't open successfully
request.onerror = function() {
  console.log('Database failed to open');
};

// onsuccess handler signifies that the database opened successfully
request.onsuccess = function() {
  console.log('Database opened successfully');

  // Store the opened database object in the db variable. This is used a lot below
  db = request.result;

  // Run the displayData() function to display the notes already in the IDB
  displayData();
};

// Setup the database tables if this has not already been done
request.onupgradeneeded = function(e) {
  // Grab a reference to the opened database
  let db = e.target.result;

  // Create an objectStore to store our notes in (basically like a single table)
  // including a auto-incrementing key
  let objectStore = db.createObjectStore('notes', { keyPath: 'id', autoIncrement:true });

  // Define what data items the objectStore will contain
  objectStore.createIndex('title', 'title', { unique: false });
  objectStore.createIndex('body', 'body', { unique: false });

  console.log('Database setup complete');
};

// Create an onsubmit handler so that when the form is submitted the addData() function is run
form.onsubmit = addData;
// Define the addData() function
function addData(e) {
	...
  // open a read/write db transaction, ready for adding the data
  let transaction = db.transaction(['notes'], 'readwrite');

  ...
}

};

运行结果

Failed to exectue ‘transaction’ on ‘IDBDatabase’: One of the specified stores was not found.

错误原因

当为open方法传入一个本域没有的数据库名时,会创建相应的数据库,并触发success、upgradeneeded事件,从而创建一个objectStore。但是,chrome54并不会触发upgradeneeded事件,造成objectStoret不会被创建,后续在objectStore上创建事务并操作数据时候就会报错。解决办法是,在open方法传入第二个参数(与已有version不同,且更大,通常是在原有的基础上加一),上面的例子中把open的第二个参数改成2即可,这样就会触发chrome上的upgradeneeded事件了。

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值