简体   繁体   中英

How do I check if an IndexedDB database already exists?

I'm working on restaurant website (client-side project) and facing this problem, I want to make an admin page will show me all the orders placed by the customers and the way I choose that to save the order details in local storage then save it in this indexedDB then display the (the orders) at the admin page so I made this code and it work all good I guess to save the order and all customer details

document.getElementById('submittheorder').onclick = function() {
    let i = 0;
    const versionDB = 1;

    let indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;

    var open = indexedDB.open("CustomersOrders", versionDB);

    open.onupgradeneeded = function() {
        let db = open.result;
        let store = db.createObjectStore("OrdersTable", {
            keyPath: "id"
        });
        let index = store.createIndex("CIndex", ["FullName", "Order", "House", "Road", "Block"]);
    };

    open.onsuccess = function() {

        let db = open.result;

        let tx = db.transaction("OrdersTable", "readwrite");

        let store = tx.objectStore("OrdersTable");

        let index = store.index("CIndex");

        store.put({
            FullName: (sessionStorage.getItem("Cfullname")),
            Order: (sessionStorage.getItem("order")),
            House: (sessionStorage.getItem("CHouse")),
            Road: (sessionStorage.getItem("CRoad")),
            Block: (sessionStorage.getItem("CBlock"))
        });


        tx.oncomplete = function() {
            db.close();
            location.href = "Thanks.html";
        };
    }
}

Now the problem is I want to retrieve all the orders and the details for each object to the admin page the second problem is that i want to check if the database already exist then insert new object not make a new database and save only one object, in a nutshell i want only one database to make and next times save the orders at that database.

Thank you:)

You can place this logic in the function that handles an upgrade event. There are essentially two ways. You can check if object stores and indices exist, using for example db.objectStoreNames.contains() , or you can compare versions by accessing the version properties from the database object or the event object.

For example, you would want to only create an object store if it did not already exist. If it does not already exists, then you know this is when your database is created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM