admin管理员组

文章数量:1427478

I have two questions : 1. I want when i update version of my DB clear all data .

objectStore.clear();

but i have got error : main1.js:42 Uncaught ConstraintError: Failed to execute 'createObjectStore' on 'IDBDatabase': An object store with the specified name already exists.

  1. How when update version DB only added new items to my Db ?

    var browserDatabase={};

    browserDatabase._db = null;
    browserDatabase._dbVersion = 4;
    browserDatabase._dbName = "mediaStorageDB";
    browserDatabase._storeName = "myStore";
    var idb = window.indexedDB
    
    var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;
    var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;
    
    var dbName='nameDb';
    
    if (!window.indexedDB) {
       // window.alert("Ваш браузер не поддерживат стабильную версию IndexedDB. Такие-то функции будут недоступны");
    }
    var request = window.indexedDB.open("MyTestDatabase", 7);
    
    
    request.onupgradeneeded = function(e) {
    
        console.log( e.oldVersion )
    
        db = event.target.result;
        //console.log(db)
        // Создаем хранилище объектов для этой базы данных
       // var objectStore = db.createObjectStore("name", { keyPath: "myKey" })
        const customerData = [
            { ssn: "444-44-4444", name: "Bill", age: 35, email: "[email protected]" },
            { ssn: "555-55-5555", name: "Donna", age: 32, email: "[email protected]" }
        ];
    
    
    
        var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
    
        // Create an index to search customers by name. We may have duplicates
        // so we can't use a unique index.
        objectStore.createIndex("name", "name", { unique: false });
    
        // Create an index to search customers by email. We want to ensure that
        // no two customers have the same email, so use a unique index.
        objectStore.createIndex("email", "email", { unique: true });
    
    
        objectStore.clear(); //clear previous version
    
    
    
        // Store values in the newly created objectStore.
        for (var i in customerData) {
            objectStore.add(customerData[i]);
        }
    
        if (e.oldVersion < 1) {
            // create v1 schema
        }
        if (e.oldVersion < 2) {
            // upgrade v1 to v2 schema
        }
        if (e.oldVersion < 3) {
            // upgrade v2 to v3 schema
        }
        // ...
    };
    request.onerror = function(event) {
        // Сделать что-то при ошибке request.errorCode!
        console.log('error');
        console.log(event);
    };
    request.onsuccess = function(event) {
        // Выполнить какой-то код если запрос успешный request.result!
        console.log('success');
    
        db = event.target.result;
        console.log(db);
    
        var transaction = db.transaction(["customers"], "readwrite");
    
    
        const customerData = [
            { ssn: "888-44-4444", name: "Sasga", age: 35, email: "[email protected]" },
            { ssn: "99-55-5555", name: "Andrii", age: 32, email: "[email protected]" }
        ];
        var objectStore = transaction.objectStore("customers");
        for (var i in customerData) {
            var request = objectStore.add(customerData[i]);
            request.onsuccess = function(event) {
                // event.target.result == customerData[i].ssn;
            };
        }
    
    
        transaction.onplete = function(event) {
            console.log("All done!");
        };
    
        transaction.onerror = function(event) {
            // Don't forget to handle errors!
        };
    
    
    };
    

I have two questions : 1. I want when i update version of my DB clear all data .

objectStore.clear();

but i have got error : main1.js:42 Uncaught ConstraintError: Failed to execute 'createObjectStore' on 'IDBDatabase': An object store with the specified name already exists.

  1. How when update version DB only added new items to my Db ?

    var browserDatabase={};

    browserDatabase._db = null;
    browserDatabase._dbVersion = 4;
    browserDatabase._dbName = "mediaStorageDB";
    browserDatabase._storeName = "myStore";
    var idb = window.indexedDB
    
    var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;
    var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;
    
    var dbName='nameDb';
    
    if (!window.indexedDB) {
       // window.alert("Ваш браузер не поддерживат стабильную версию IndexedDB. Такие-то функции будут недоступны");
    }
    var request = window.indexedDB.open("MyTestDatabase", 7);
    
    
    request.onupgradeneeded = function(e) {
    
        console.log( e.oldVersion )
    
        db = event.target.result;
        //console.log(db)
        // Создаем хранилище объектов для этой базы данных
       // var objectStore = db.createObjectStore("name", { keyPath: "myKey" })
        const customerData = [
            { ssn: "444-44-4444", name: "Bill", age: 35, email: "[email protected]" },
            { ssn: "555-55-5555", name: "Donna", age: 32, email: "[email protected]" }
        ];
    
    
    
        var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
    
        // Create an index to search customers by name. We may have duplicates
        // so we can't use a unique index.
        objectStore.createIndex("name", "name", { unique: false });
    
        // Create an index to search customers by email. We want to ensure that
        // no two customers have the same email, so use a unique index.
        objectStore.createIndex("email", "email", { unique: true });
    
    
        objectStore.clear(); //clear previous version
    
    
    
        // Store values in the newly created objectStore.
        for (var i in customerData) {
            objectStore.add(customerData[i]);
        }
    
        if (e.oldVersion < 1) {
            // create v1 schema
        }
        if (e.oldVersion < 2) {
            // upgrade v1 to v2 schema
        }
        if (e.oldVersion < 3) {
            // upgrade v2 to v3 schema
        }
        // ...
    };
    request.onerror = function(event) {
        // Сделать что-то при ошибке request.errorCode!
        console.log('error');
        console.log(event);
    };
    request.onsuccess = function(event) {
        // Выполнить какой-то код если запрос успешный request.result!
        console.log('success');
    
        db = event.target.result;
        console.log(db);
    
        var transaction = db.transaction(["customers"], "readwrite");
    
    
        const customerData = [
            { ssn: "888-44-4444", name: "Sasga", age: 35, email: "[email protected]" },
            { ssn: "99-55-5555", name: "Andrii", age: 32, email: "[email protected]" }
        ];
        var objectStore = transaction.objectStore("customers");
        for (var i in customerData) {
            var request = objectStore.add(customerData[i]);
            request.onsuccess = function(event) {
                // event.target.result == customerData[i].ssn;
            };
        }
    
    
        transaction.onplete = function(event) {
            console.log("All done!");
        };
    
        transaction.onerror = function(event) {
            // Don't forget to handle errors!
        };
    
    
    };
    
Share Improve this question asked Mar 3, 2017 at 9:02 zloctbzloctb 11.2k10 gold badges77 silver badges91 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

clear will delete all data in a store.

deleteObjectStore will delete the store.

You're getting an error because a store already exists and you're trying to create it. If you want to be able to run create, you have to deleteObjectStore first.

However this probably isn't ultimately what you want to do. In version changes, you generally don't want to delete your object stores, indexes, and data. You just want to update them.

本文标签: javascriptHow clear all data from indexedDB when update versionStack Overflow