Failed to execute 'createObjectStore' on 'IDBDatabase'
Asked Answered
C

2

32

why do I have a error ?

My code:

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
};

Uncaught InvalidStateError: Failed to execute 'createObjectStore' on 'IDBDatabase': The database is not running a version change transaction. index.html:37 idbRequest.onsuccess

Cilurzo answered 24/6, 2014 at 8:44 Comment(2)
"Що це за" - what does it mean? :DScoter
I understand all your comments expect this :-)Scoter
P
56

You can't create an objectStore in an onsuccess method. You can only do this in a upgradeneeded event.

Quote from docs:

When you create a new database or increase the version number of an existing database (by specifying a higher version number than you did previously, when Opening a database), the onupgradeneeded event will be triggered. In the handler for this event, you should create the object stores needed for this version of the database

See documentation.

Puccoon answered 25/6, 2014 at 6:56 Comment(5)
What if populating data failed in onupgradeneeded?Widen
So should I do data verification in onsuccess, if the data is not valid, then open the db with a higher version to trigger the onupgradeneeded again?Widen
user1663023, consider 'db version' as set of tables/fields. And you can change this set in onupgradeneeded event only.Pink
You can read/write data in onsuccess event as well in onupgradeneeded.Pink
Good to me. open.onupgradeneeded = () => { open.result.createObjectStore('STORE_NAME') }Scolex
T
0
    try creating your objectStore on onupgradeneeded event:

request.onupgradeneeded = (event: any) => {
      const db = event.target.result;
      if(!db.objectStoreNames.contains(this.currentObjectStore)){
        db.createObjectStore(this.currentObjectStore);
      }
    };
Tutti answered 30/1 at 6:47 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Chart

© 2022 - 2024 — McMap. All rights reserved.