luperxe
luperxe

Reputation: 71

Why is onupgradeneeded never called in this code?

I'm trying to insert data in my indexed db, but the function onupgradeneed never is called, just onsuccess. The version of the database is always the same (it is a global variable). I have understood that in order to get into onupgradeneed the version have to be always the same. In my case, it is in this way. So, I have no data... What can I do? Thanks!

var db;
var dbname = "mi";
var dbversion = 1;

function abrirDB()
{
    if (plataforma == plataformaW8) {
        if (db == null) {
            var request = window.indexedDB.open(dbname, dbversion);
            request.onsuccess = function (evt) {
                db = evt.target.result;
                if (db.objectStoreNames.length == 0)
                    crearDB();
            };
            }
        }
}
function crearDB() {


   //Declaración datos BBDD

        var paisesData = [{ id_pais: 1, pais: "Arabia Saudí", continente: "Asia", capital: "Riad", paisurl: "arabiasaudi", continenteurl: "asia" },
      { id_pais: 2, pais: "Emiratos Árabes Unidos", continente: "Asia", capital: "Abu Dhabi", paisurl: "emiratosarabes", continenteurl: "asia" }];


    //////////

    //Abrir BBDD
    var request =window.indexedDB.open(dbname, dbversion);

    request.onerror = function (evt) {
        console.log("Error al abrir la bbdd" + evt.target.errorCode);
    };


    request.onupgradeneeded = function (evt) {
       db = evt.target.result;

        var storePaises = db.createObjectStore(storePaisesNombre, { keyPath: "id_pais", autoincrement: false, unique: true });
      .......
    request.onsuccess = function (evt) {
        //db = request.result;
        db = evt.target.result;
    };

  }

Upvotes: 5

Views: 8601

Answers (3)

NATALIAGJ
NATALIAGJ

Reputation: 121

you can change version 1 for two, it worked for me like this:

let openRequest = window.indexedDB.open ("MyTestDatabase", 2);

Upvotes: 2

Kristof Degrave
Kristof Degrave

Reputation: 4180

Change your dbversion variable to 2. This way the db will open in a newer version and the onupgradeneeded callback will get called

Upvotes: 3

Josh
Josh

Reputation: 18720

Stop using a global db variable, even if some examples show it. It just leads to problems for newer programmers. Try reviewing my answer at How to get objectstore from indexedDB? for help.

Upvotes: -1

Related Questions