Search code examples
javascriptindexeddbdexie

IndexedDB - Dexie JS : Dynamically create stores


I'm working with indexedDB for local data storage, with Dexie.js which is pretty nice as a wrapper, especially because of the advanced queries. Actually, I would like to create to create several datastore by script, which seem complicated.

To create a new store, you would do something like :

db.version(2).stores({
    Doctors: "++" + strFields
});

If I do something like Doctors = "Hospital", it still creates the store with a name "Doctors".

Is there a way to do this?

Did anybody faced the same problem?


Solution

  • Let's say you want three object stores "Doctors", "Patients" and "Hospitals", you would write something like:

    var db = new Dexie ("your-database-name");
    db.version(1).stores({
        Doctors: "++id,name",
        Patients: "ssn",
        Hospitals: "++id,city"
    });
    db.open();
    

    Note that you only have to specify the primary key and the required indexes. Primary key can optionally be auto-incremented ("++" prefixed). You could add as many properties to your objects as you wish without having to specify each one in the index list.

    db.Doctors.add({name: "Phil", shoeSize: 83});
    db.Patients.add({ssn: "721-07-446", name: "Randle Patrick McMurphy"});
    db.Hospitals.add({name: "Johns Hopkins Hospital", city: "Baltimore"});
    

    And to query different stores:

    db.Doctors.where('name').startsWithIgnoreCase("ph").each(function (doctor) {
        alert ("Found doctor: " + doctor.name);
    });
    
    db.Hospitals.where('city').anyOf("Baltimore", "NYC").toArray(function (hospitals) {
       alert ("Found hospitals: " + JSON.stringify(hospitals, null, 4));
    });