dexie.js 使用上的问题
2020-06-28 本文已影响0人
CRJ997
详细的使用教程实际上都可以在官网上看到,我这边记录一些问题。
1. dexie.version()
这个东西在一开始创建数据库的时候就要用上,但是用了之后就感觉很奇怪。使用官网的快速开始例子:
<!doctype html>
<html>
<head>
<script src="https://unpkg.com/dexie@latest/dist/dexie.js"></script>
<script>
//
// Declare Database
//
var db = new Dexie("FriendDatabase");
db.version(1).stores({
friends: "++id,name,age"
});
//
// Manipulate and Query Database
//
db.friends.add({name: "Josephine", age: 21}).then(function() {
return db.friends.where("age").below(25).toArray();
}).then(function (youngFriends) {
alert ("My young friends: " + JSON.stringify(youngFriends));
}).catch(function (e) {
alert ("Error: " + (e.stack || e));
});
</script>
</head>
</html>
然后去开发者工具中看的时候,版本却是10。详情见图1
图1
哦豁,什么情况,1直接跳过,变成10?然后去官网找答案。发现还真有: Dexie.version().好像是因为一些原因,所以会把输入的数字乘以10然后再向下取整。
2. dexie打开已经存在的数据库
一开始以为使用new Dexie('databaseName');
,就会自动判别是已经存在的数据库还是新的。然后写了下面的代码进行测试:
var db = new Dexie('FriendDatabase');
db.version(0.1).stores({
friends: "++id,name,age"
});
db = new Dexie('FriendDatabase');
发现创建的表给清空了,好吧,还是去官网找答案:Dexie,链接无用的话,详细的代码如下:
// 创建新的数据库
// Declare db instance
var db = new Dexie("MyDatabase");
// Define Database Schema
db.version(1).stores({
friends: "++id, name, age, isCloseFriend",
notes: "++id, title, date, *items"
});
// Interact With Database
db.transaction('rw', db.friends, db.notes, function* () {
// Let's add some data to db:
var friend1Id = yield db.friends
.add({name: 'Camilla', age: 25, isCloseFriend: 1});
var friend2Id = yield db.friends
.add({name: 'Ban Ki-moon', age: 70, isCloseFriend: 0});
var noteId = yield db.notes.add({
title: 'Shop tomorrow',
date: new Date(),
items: ['milk', 'butter']
});
// Let's query the db
var closeFriends = yield db.friends
.where('isCloseFriend').equals(1)
.toArray();
console.log("Close friends:" + closeFriends.map(f => f.name));
var toShop = yield db.notes
.where('title').startsWithIgnoreCase ('shop')
.toArray();
console.log("Shopping list: " + toShop.map(note => note.items));
}).catch(function(err) {
// Catch any error event or exception and log it:
console.error(err.stack || err);
});
// 打开已经存在的数据库
new Dexie('MyDatabase').open().then(function (db) {
console.log ("Found database: " + db.name);
console.log ("Database version: " + db.verno);
db.tables.forEach(function (table) {
console.log ("Found table: " + table.name);
console.log ("Table Schema: " +
JSON.stringify(table.schema, null, 4));
});
}).catch('NoSuchDatabaseError', function(e) {
// Database with that name did not exist
console.error ("Database not found");
}).catch(function (e) {
console.error ("Oh uh: " + e);
});
3. 什么时候要对indexDB进行upgrade
这个应该是indexDB的问题,不过Dexie本来就是为了更方便的操作IndexDB才出来的,就记录在这里了。
答案很简单:就是在需要新增,删除表或者表的列的时候,就需要进行升级。或者说,在需要更改数据库的schema的时候,就需要进行版本的升级。