How to create multiple object stores in IndexedDB

I do not know if I am right or not. But, as I know, I cannot create a version change transaction manually. The only way to call this is to change the version number when opening an indexed database connection. If this is correct, will the new Store object never be created in Example 1 and Example 2?

Example 1

function createObjectStore(name){ var request2 = indexedDB.open("existingDB"); request2.onupgradeneeded = function() { var db = request2.result; var store = db.createObjectStore(name); }; } 

Example 2

 function createObjectStore(name){ var request2 = indexedDB.open("existingDB"); request2.onsuccess = function() { var db = request2.result; var store = db.createObjectStore(name); }; } 

Example3 - This should work:

 function createObjectStore(name){ var request2 = indexedDB.open("existingDB", 2); request2.onupgradeneeded = function() { var db = request2.result; var store = db.createObjectStore(name); }; } 

If I want to create several Store objects in the same database , how can I get / get the database version before opening the database? So is there a way to automate this process of getting the database version number?

Is there any other way to create an objectStore other than this using the onupgradedededed handler.

Please, help. Many thanks.

Edit:

Here is the same problem as mine: https://groups.google.com/a/chromium.org/forum/#!topic/chromium-html5/0rfvwVdSlAs

+7
javascript indexeddb
source share
2 answers

You need to open the database to check its current version, and reopen it with version + 1 to start the update.

Here is a sample code:

 function CreateObjectStore(dbName, storeName) { var request = indexedDB.open(dbName); request.onsuccess = function (e){ var database = e.target.result; var version = parseInt(database.version); database.close(); var secondRequest = indexedDB.open(dbName, version+1); secondRequest.onupgradeneeded = function (e) { var database = e.target.result; var objectStore = database.createObjectStore(storeName, { keyPath: 'id' }); }; secondRequest.onsuccess = function (e) { e.target.result.close(); } } } 
+15
source share

The only way to create an object store is with the onupgradedededededed event. To change the schema, transaction version_change is required. And the only way to get the version_change transaction is through the onupgradedededed event.

The only way to trigger the onupgradeneeded event is to open the database in a higher version than the current version of the database. The best way to do this is to keep the constant with the current version of the database that you need to work with. Each time you need to change the database schema, you increase this number. Then in the onupgradededed event you can get the current version of the database. In this case, you can decide which upgrade path you need to follow in order to go to the latest database schema.

Hope this answers your question.

+5
source share

All Articles