Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

javascript - How to create multiple object stores in IndexedDB

I don't know if I'm right or wrong. But as I know I can't create a version change transaction manually. The only way to invoke this is by changing the version number when opening the indexed DB connection. If this is correct, in example1 and example2 new objectStore will never be created?

Example1

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

Example2

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 multiple objectStore's in one database how can I get/fetch database version before opening the database?? So is there a way to automate this process of getting database version number??

Is there any other way to create objectStore other than that using onupgradeneeded event handler.

Please help. Thanks a lot.

Edit:

Here is same problem that I have: https://groups.google.com/a/chromium.org/forum/#!topic/chromium-html5/0rfvwVdSlAs

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to open the database to check it's current version and open it again with version + 1 to trigger the upgrade.

Here is the 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();
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...