Skip to content

Dexie.version()

David Fahlander edited this page Mar 27, 2014 · 13 revisions

Syntax

db.version(versionNumber)

Parameters

versionNumber : Number The version to declare

Return Value

Version

See Also

Design#database-versioning

Sample

This sample shows how to upgrade your database. Assume your first app defines version 1 of the database like this:

var db = new Dexie("FriendsAndPetsDatabase");
db.version(1).stores({
    friends: "++id,name,age",
    pets: "++id,name,kind"
});
db.open(); 

// Do some application logic on the database:
db.transaction("rw", db.friends, db.pets, function (friends, pets) {
    friends.add({name: "David", age: 40, sex: "male"});
    friends.add({name: "Ylva", age: 39, sex: "female"});
    pets.add({name: "Josephina", kind: "dog"});

    friends.where("name").equalsIgnoreCase("david").each(function(friend) {
        console.log("Found friend: " + friend.name);
    });
    pets.where("kind").anyOf("dog", "cat").each(function(pet) {
        console.log("Found dog or cat: " + pet.name);
    });
}).catch (function (e) {
    console.error(e.stack || e);
});

Then you realise "age" was not a good thing to store because it will change as time goes by. You want to redesign your app to store birthdate instead. Here is how version 2 of your released app would look:

var db = new Dexie("FriendsAndPetsDatabase");
db.version(2).stores({
    friends: "++id,name,birthdate,sex",
    pets: "++id,name,kind"
}).upgrade (function (trans) {
    var YEAR = 365 * 24 * 60 * 60 * 1000;
    trans.friends.each (function (friend, cursor) {
        friend.birthdate = new Date(Date.now() - (friend.age * YEAR));
        delete friend.age;
        cursor.update (friend);
    });
});
// Always keep the declarations previous versions as long as there might be users having them running.
db.version(1).stores({
    friends: "++id,name,age,sex",
    pets: "++id,name,kind"
});
db.open(); 
Clone this wiki locally