无法在'IDBDatabase'上执行'createObjectStore'

Mic*_*lps 12 javascript indexeddb

为什么我有错误?

我的代码:

var idb = window.indexedDB ||      // Use the standard DB API
          window.mozIndexedDB ||   // Or Firefox's early version of it
          window.webkitIndexedDB;  // Or Chrome's early version

var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;
var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;

var dbName='nameDb';

var idbRequest=idb.open(dbName,'4.67' /*,dbDescription  */);

idbRequest.onsuccess=function (e) {
    debugger

    var db=e.target.result; 

    if (!db.objectStoreNames.contains('chat')){
        co=db.createObjectStore('chat',{'id':100});
    };

    if (!db.objectStoreNames.contains('iam')){
        co1=db.createObjectStore('iam');
    }; 
};

idbRequest.onerror = function (e) {
    debugger
};
Run Code Online (Sandbox Code Playgroud)

未捕获的InvalidStateError:无法在"IDBDatabase"上执行"createObjectStore":数据库未运行版本更改事务.index.html:37 idbRequest.onsuccess

Dic*_*ink 25

您无法在success命令中创建objectStore.您只能在升级所需的事件中执行此操作.

从文档引用:

当您创建新数据库或增加现有数据库的版本号时(通过指定比以前更高的版本号,在打开数据库时),将触发onupgradeneeded事件.在此事件的处理程序中,您应该创建此版本数据库所需的对象库

文档.

  • 那么我是否应该在onsuccess中做数据验证,如果数据无效,然后打开更高版本的db再次触发onupgradeneeded? (2认同)