我想将表中的所有项目提取到集合中,但收到表名称为undefined
的错误消息。这是我的商店:
db.version(1).stores({
users: '++id,',
orgs: '++id,',
applications: '++id'
})
然后稍后是我的电话:
db.orgs.toCollection().count(function (count) {
console.log(count)
})
它出现以下错误:
TypeError: Cannot read property 'toCollection' of undefined
但是当我在调用时停止调试器并输入db.tables
时,就足够确定了:
1:Table {name: "orgs", schema: TableSchema, _tx: undefined, …}
_tx:undefined
hook:function rv(eventName, subscriber) { … }
name:"orgs"
感谢您的帮助-谢谢。
更新
我注意到,当我在初始创建时为数据库添加种子时,可以取出数据。因此,我将该代码复制到了模板中。但是它仍然失败,因此肯定缺少一些简单的东西,这是该代码:
import Dexie from '@/dexie.es.js'
export default {
name: 'ListOrgs',
data: () => {
return {
orgs: []
}
},
methods: {
populateOrgs: async function () {
let db = await new Dexie('myDatabase').open()
db.orgs.toCollection().count(function (count) {
console.log(count)
})
}
},
mounted () {
this.populateOrgs()
}
}
答案 0 :(得分:2)
Dexie有两种模式
//
// Static Mode
//
const db = new Dexie('myDatabase');
db.version(1).stores({myTable1: '++'});
db.version(2).stores({myTable1: '++, foo'});
db.myTable1.add({foo: 'bar'}); // OK - dexie knows about myTable1!
//
// Dynamic Mode
//
const db = new Dexie('myDatabase');
// FAIL: db.myTable1.add({foo: 'bar'}); // myTable1 is unknown to the API.
// Here, you must wait for db to open, and then access tables using db.table() method:
db.open().then(db => {
const myTable = db.table('myTable');
if (myTable) {
myTable.add({foo: 'bar'});
}
}).catch(error => {
console.error(error);
});
如果省略任何version()规范,则Dexie将尝试打开任何具有相同名称的现有数据库,无论版本或架构如何。但这不会在数据库实例上创建隐式表属性。
动态模式在构建应适应任何indexedDB数据库(例如DB Explorer)的数据库实用程序时非常有用。当javascript代码在设计上不了解架构(期望查询哪些表以及存在哪些索引)时,动态模式也很有用。
db.js
import Dexie from 'dexie';
//
// Let this module do several things:
//
// * Create the singleton Dexie instance for your application.
// * Declare it's schema (and version history / migrations)
// * (Populate default data http://dexie.org/docs/Dexie/Dexie.on.populate)
//
export const db = new Dexie('myDatabase');
db.version(1).stores({
users: '++id,',
orgs: '++id,',
applications: '++id'
});
db.on('populate', () => {
return db.orgs.bulkAdd([
{'foo': 'bar'},
]);
});
app.js
import {db} from './db';
// Wherever you use the database, include your own db module
// instead of creating a new Dexie(). This way your code will
// always make sure to create or upgrade your database whichever
// of your modules that comes first in accessing the database.
//
// You will not have to take care of creation or upgrading scenarios.
//
// Let Dexie do that for you instead.
//
async function countOrgs() {
return await db.orgs.count();
}