0

Let's say I create a very simple datastore using the steps below:

  1. var db = new Dexie('MyDatabase');

  2. db.version(1).stores({ friends: 'name, age' });

  3. db.friends.add({ name: 'Camilla', age: 25 });

Now, let’s say the user closes their browser and comes back a day later and we need to query the data that we already saved in a datastore that should already exist. Do I need to include both line 1 and line 2 each time before I query the datastore or insert new rows? I’m confused about when I’m required to execute line 2 – is it basically before I do anything to/with the datastore?

4

1 回答 1

1

您通常会在每次打开数据库时提供 db.version(x).stores({...}),无论它是需要创建、升级还是刚刚打开。通过提供此信息,您将可以直接在 db 对象上直接访问您的表(例如访问 db.friends.toArray() 而无需等待 db.open() 完成),如下所示:

var db = new Dexie("friendsDB");
db.version(1).stores({friends: 'id, name'});
// Here you can just access db.friends without waiting for db.open()
db.friends.toArray()
   .then(friends => console.table(friends))
   .catch(err => console.error(err));

但是,也可以动态地打开数据库——也就是说,在不知道其表或索引的情况下打开现有数据库。为此,您只需省略 version().stores() 部分。请注意,您将无法直接在 db 实例上访问表,并且您不会获得数据库的神奇自动创建功能。需要通过tables属性和table()方法访问表,并且只有在 db.open() 完成后才能访问。

new Dexie("friendsDB").open().then(db => {
    console.log("Table names: " + db.tables.map(t => t.name));
    return db.table("friends").toArray();
}).then(friends => {
    console.table(friends);
}).catch(err => console.error(err));
于 2017-03-31T23:33:46.327 回答