IndexedDB - Dexie JS : Dynamically create stores

江枫思渺然 提交于 2019-12-11 00:29:38

问题


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?


回答1:


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));
});


来源:https://stackoverflow.com/questions/26995810/indexeddb-dexie-js-dynamically-create-stores

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!