对于我的应用程序,我希望用户能够为表指定索引列。
我认识到,为了做到这一点,我需要关闭数据库,指定一个新版本,然后再打开它。为了最小化这样做的影响,我将应用程序的这个自定义部分放在自己的数据库中。
下面是我如何做到这一点的一个例子。
import Dexie from 'dexie';
const db = new Dexie("CustomPeople");
db.version(1).stores({
people: '++id'
});
function testColumnAdd() {
modifyColumns(['firstName'])
.then(() => {
db.people.add({
firstName: 'John'
});
})
.then(() => {
return modifyColumns(['firstName', 'lastName']);
})
.then(() => {
db.people.add({
firstName: 'John',
lastName: 'Smith'
});
});
}
function modifyColumns(columns) {
return db.open()
.then(() => {
const originalVersion = db.verno;
console.log('original version: ' + originalVersion);
db.close();
return originalVersion;
})
.then((originalVersion) => {
const newVersion = originalVersion + 1;
console.log('adding columns ' + columns.join(','));
console.log('new version version ' + newVersion);
db.version(newVersion).stores({
leads: '++id,' + columns.join(',')
});
return db.open();
});
}每次调用testColumnAdd()时,这似乎都很好。
但是,在重新加载页面之后,testColumnAdd()的第一个触发器会出现以下异常。
Unhandled rejection: VersionError: The requested version (10) is less than the existing version (70).考虑到德克茜最初看到的都是版本1,这无疑是有意义的。有什么方法可以让我读到当前版本并使用它吗?
一般来说,是否有更好的方法来处理用户定义的索引?
发布于 2018-07-10 01:58:04
我不确定这是否最初的意图,但我找到了另一种方法来初始化一个现有的数据库。
出于其他原因,我需要将列的定义存储在单独的数据库中。在加载现有数据库时,我只需根据该元数据构建正确的版本。
const dbName = 'CustomPeople';
const exists = await Dexie.exists(dbName);
if (exists) {
var db = new Dexie(dbName);
const dynamicDB = await db.open();
const existingVersionNumber = dynamicDB.verno;
const columns = await ExternalDBService.getColumns();
db.close();
db = new Dexie(dbName);
db.version(existingVersionNumber).stores({
People: columns
});
return db.open();
} else {
db = new Dexie(dbName);
db.version(1).stores({
People: []
});
db.open();
}发布于 2018-06-14 13:03:19
德克茜有一个动态模式。它是通过省略db.version(x)的规范来启用的。它基本上将数据库打开到当前版本。
new Dexie("CustomPeople").open().then (db => {
console.log("Version", db.verno);
console.log("Tables", db.tables.map(({name, schema}) => ({
name,
schema
}));
});但是,当您需要修改模式(或最初创建它)时,您必须按照您已经做的那样做--在打开它之前指定db.version(db.verno + 1)。
更改模式需要重新打开数据库的原因是IndexedDB本身的限制/特性。
编辑:我刚刚更新了docs:http://dexie.org/docs/Dexie/Dexie.open()#dynamic-schema-manipulation
https://stackoverflow.com/questions/50849381
复制相似问题