database.md 37.6 KB
Newer Older
W
wanganxp 已提交
1
## clientDB简介
雪洛's avatar
雪洛 已提交
2

W
wanganxp 已提交
3
> 自`HBuilderX 2.9.5`起支持在客户端直接使用`uniCloud.database()`方式获取数据库引用,即在前端直接操作数据库,这个功能被称为clientDB
W
wanganxp 已提交
4
> 2.9.5以前的用户如使用过clientDB,再升级后请将clientDB的前端库和云函数删除,新版已经在前端和云端内置了clientDB
雪洛's avatar
雪洛 已提交
5

W
wanganxp 已提交
6
使用`clientDB`的好处:**不用写服务器代码了!**
雪洛's avatar
雪洛 已提交
7

W
wanganxp 已提交
8
1个应用开发的一半的工作量,就此直接省去。
W
wanganxp 已提交
9

W
wanganxp 已提交
10
当然使用`clientDB`需要扭转传统后台开发观念,不再编写云函数,直接在前端操作数据库。但是为了数据安全,需要在数据库上配置schema。
W
wanganxp 已提交
11

W
wanganxp 已提交
12
`db schema`中,配置数据操作的权限和校验规则,阻止前端不恰当的数据读取和写入。参考:[DB-schema](https://uniapp.dcloud.net.cn/uniCloud/schema)
W
wanganxp 已提交
13

W
wanganxp 已提交
14
如果想在数据库操作之前或之后需要在云端执行额外的动作(比如获取文章详情之后阅读量+1),`clientDB`提供了action机制。在HBuilderX项目的`cloudfunctions/uni-clientDB-actions`目录编写上传js,参考:[actions](uniCloud/database?id=actions)
雪洛's avatar
雪洛 已提交
15 16 17

**注意**

W
wanganxp 已提交
18 19
- `clientDB`依赖uni-id提供用户身份和权限校验,如果你不了解uni-id,请参考[uni-id文档](https://uniapp.dcloud.net.cn/uniCloud/uni-id)
- 通常在管理控制台使用`clientDB`,需要获取不同角色用户拥有的权限(在权限规则内使用auth.permission),请先查阅[uni-id 角色权限](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=rbac)
雪洛's avatar
雪洛 已提交
20

W
wanganxp 已提交
21 22 23
## clientDB图解
![](https://static-eefb4127-9f58-4963-a29b-42856d4205ee.bspapp.com/clientdb.jpg)

W
wanganxp 已提交
24
`clientDB`的前端部分包括js API和`<uni-clientDB>`组件两部分。
雪洛's avatar
雪洛 已提交
25

W
wanganxp 已提交
26
js API可以执行所有数据库操作。`<uni-clientDB>`组件适用于查询数据库,它是js API的再封装,进一步简化查询的代码量。
雪洛's avatar
雪洛 已提交
27

W
wanganxp 已提交
28
目前`<uni-clientDB>`组件没有内置,而是作为一个插件单独下载,它的文档另见:[https://uniapp.dcloud.net.cn/uniCloud/uni-clientdb-component](https://uniapp.dcloud.net.cn/uniCloud/uni-clientdb-component)
W
wanganxp 已提交
29

W
wanganxp 已提交
30
以下文章重点介绍`clientDB`的js API,组件的查询语法与js API是一致的。
雪洛's avatar
雪洛 已提交
31

W
wanganxp 已提交
32 33 34 35 36 37 38 39 40
## clientDB前端API@jssdk

`clientDB`的客户端部分主要负责提供API,允许前端编写数据库操作指令,以及处理一些客户端不太方便表示的字段,比如用户ID(详情看下面语法扩展部分)

`clientDB`支持传统的nosql查询语法,并新增了`jql`查询语法。`jql`是一种更易用的查询语法。

**传统nosql查询语法示例**

这段示例代码,在一个前端页面,直接查询了云数据库的`list`表,并且指定了`name`字段值为`hello-uni-app`的查询条件,then里的res即为返回的查询结果。
雪洛's avatar
雪洛 已提交
41 42 43 44 45 46 47

```js
// 获取db引用
const db = uniCloud.database()
// 使用uni-clientDB
db.collection('list')
  .where({
W
wanganxp 已提交
48
    name: "hello-uni-app" //传统MongoDB写法,不是jql写法。实际开发中推荐使用jql写法
雪洛's avatar
雪洛 已提交
49 50 51 52 53 54 55 56 57 58
  }).get()
  .then((res)=>{
    // res 为数据库查询结果
  }).catch((err)=>{
    
  })
```

**使用说明**

W
wanganxp 已提交
59
前端操作数据库的语法与云函数一致,但有以下限制:
雪洛's avatar
雪洛 已提交
60 61

- 上传时会对query进行序列化,除Date类型、RegExp之外的所有不可序列化的参数类型均不支持(例如:undefined)
W
wanganxp 已提交
62
- 为方便控制权限,禁止前端使用set方法,一般情况下也不需要前端使用set
雪洛's avatar
雪洛 已提交
63 64 65 66 67
- 更新数据库时不可使用更新操作符`db.command.inc`
- 更新数据时键值不可使用`{'a.b.c': 1}`的形式,需要写成`{a:{b:{c:1}}}`形式(后续会对此进行优化)

### 返回值说明@returnvalue

W
wanganxp 已提交
68
`clientDB`云端默认返回值形式如下,开发者可以在[action](uniCloud/database?id=action)`after`内用js修改返回结果,传入`after`内的result不带code和message。
雪洛's avatar
雪洛 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

```js
{
  code: "", // 错误码
  message: "" // 错误信息
  ... // 数据库指令执行结果
}
```

**错误码列表**

|错误码													|描述																		|
|:-:														|:-:																		|
|TOKEN_INVALID_INVALID_CLIENTID	|token校验未通过(设备特征校验未通过)	|
|TOKEN_INVALID									|token校验未通过(云端已不包含此token)	|
|TOKEN_INVALID_TOKEN_EXPIRED		|token校验未通过(token已过期)					|
|TOKEN_INVALID_WRONG_TOKEN			|token校验未通过(token校验未通过)			|
雪洛's avatar
雪洛 已提交
86
|SYNTAX_ERROR										|语法错误																|
雪洛's avatar
雪洛 已提交
87 88 89 90
|PERMISSION_ERROR								|权限校验未通过													|
|VALIDATION_ERROR								|数据格式未通过													|
|SYSTEM_ERROR										|系统错误																|

雪洛's avatar
雪洛 已提交
91
### 前端环境变量@variable
雪洛's avatar
雪洛 已提交
92

W
wanganxp 已提交
93
`clientDB`目前内置了3个变量可以供客户端使用,客户端并非直接获得这三个变量的值,而是需要传递给云端,云数据库在数据入库时会把变量替换为实际值。
雪洛's avatar
雪洛 已提交
94

W
wanganxp 已提交
95 96 97 98 99
|参数名			|说明				|
|:-:			|:-:				|
|db.env.uid		|用户uid,依赖uni-id|
|db.env.now		|服务器时间戳		|
|db.env.clientIP|当前客户端IP		|
雪洛's avatar
雪洛 已提交
100 101 102

使用这些变量,将可以避免过去在服务端代码中写代码获取用户uid、时间和客户端ip的麻烦。

雪洛's avatar
雪洛 已提交
103 104 105 106 107 108 109
```js
const db = uniCloud.database()
let res = await db.collection('table').where({
  user_id: db.env.uid // 查询当前用户的数据
}).get()
```

W
wanganxp 已提交
110
### jql查询语法@jsquery
W
wanganxp 已提交
111 112 113 114 115

`jql`,全称javascript query language,是一种js方式操作数据库的语法规范。

`jql`大幅降低了js工程师操作数据库的难度、大幅缩短开发代码量。并利用json数据库的嵌套特点,极大的简化了联表查询的复杂度。

W
wanganxp 已提交
116
#### jql的诞生背景
W
wanganxp 已提交
117 118

传统的数据库查询,有sql和nosql两种查询语法。
雪洛's avatar
雪洛 已提交
119

W
wanganxp 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
- sql是一种字符串表达式,写法形如:

```
select * from table1 where field1="123"
```

- nosql是js方法+json方式的参数,写法形如:

```js
const db = uniCloud.database()
let res = await db.collection('table').where({
  field1: '123'
}).get()
```

sql写法,对js工程师而言有学习成本,而且无法处理非关系型的MongoDB数据库,以及sql的联表查询inner join、left join也并不易于学习。

而nosql的写法,实在过于复杂。
W
wanganxp 已提交
138

W
wanganxp 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
1. 运算符需要转码,`>`需要使用`gt`方法、`==`需要使用`eq`方法、
比如一个简单的查询,取field1>0,则需要如下复杂写法

```js
const db = uniCloud.database()
const dbCmd = db.command
let res = await db.collection('table1').where({
  field1: dbCmd.gt(0)
}).get()
```

如果要表达`或`关系,需要用`or`方法,写法更复杂

```js
field1:dbCmd.gt(4000).or(dbCmd.gt(6000).and(dbCmd.lt(8000)))
```

2. nosql的联表查询写法,比sql还复杂
W
wanganxp 已提交
157
sql的inner join、left join已经够乱了,而nosql的代码无论写法还是可读性,都更“令人发指”。比如这个联表查询:
雪洛's avatar
雪洛 已提交
158 159 160 161

```js
const db = uniCloud.database()
const dbCmd = db.command
W
wanganxp 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
const $ = dbCmd.aggregate
let res = await db.collection('orders').aggregate()
.lookup({
  from: 'books',
  let: {
    order_book: '$book',
    order_quantity: '$quantity'
  },
  pipeline: $.pipeline()
    .match(dbCmd.expr($.and([
      $.eq(['$title', '$$order_book']),
      $.gte(['$stock', '$$order_quantity'])
    ])))
    .project({
      _id: 0,
      title: 1,
      author: 1,
      stock: 1
    })
    .done(),
  as: 'bookList',
})
.end()
```

W
wanganxp 已提交
187 188 189
3. 列表分页写法复杂
需要使用skip,处理offset

W
wanganxp 已提交
190 191 192 193 194 195 196 197
这些问题竖起一堵墙,让后端开发难度加大,成为一个“专业领域”。但其实这堵墙是完全可以推倒的。

`jql`将解决这些问题,让js工程师没有难操作的数据。

具体看以下示例

```js
const db = uniCloud.database()
雪洛's avatar
雪洛 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210

// 上面的示例中的where条件可以使用以下写法
db.collection('list')
  .where('name == "hello-uni-app"')
  .get()
  .then((res)=>{
    // res 为数据库查询结果
  }).catch((err)=>{
    // err.message 错误信息
    // err.code 错误码
  })
```

W
wanganxp 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224
除了js写法,uniCloud还提供了`<uni-clientdb>`组件,可以在前端页面中直接查询云端数据并绑定到界面上。[详情](https://ext.dcloud.net.cn/plugin?id=3256)
比如下面的代码,list表中查询到符合条件的记录可以直接绑定渲染到界面上

```html
<uni-clientdb v-slot:default="{loading, data, error, options}" :options="options"
 collection="list" where='name == "hello-uni-app"' :getone="true">
	<view v-if="error" class="error">{{error}}</view>
	<view v-else>
		{{item.name}}
	</view>
	<view class="loading" v-if="loading">加载中...</view>
</uni-clientdb>
```

雪洛's avatar
雪洛 已提交
225
**jql条件语句内变量**
W
wanganxp 已提交
226

雪洛's avatar
雪洛 已提交
227
以下变量同[前端环境变量](uniCloud/database.md?id=variable)
W
wanganxp 已提交
228

雪洛's avatar
雪洛 已提交
229 230 231 232 233
|参数名			|说明				|
|:-:			|:-:				|
|$env.uid		|用户uid,依赖uni-id|
|$env.now		|服务器时间戳		|
|$env.clientIP|当前客户端IP		|
W
wanganxp 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

**jql条件语句的运算符**

|运算符			|说明			|示例								|示例解释(集合查询)																		|
|:-:			|:-:			|:-:								|:-:																					|
|==				|等于			|name == 'abc'						|查询name属性为abc的记录,左侧为数据库字段												|
|!=				|不等于			|name != 'abc'						|查询name属性不为abc的记录,左侧为数据库字段											|
|>				|大于			|age>10								|查询条件的 age 属性大于 10,左侧为数据库字段											|
|>=				|大于等于		|age>=10							|查询条件的 age 属性大于等于 10,左侧为数据库字段										|
|<				|小于			|age<10								|查询条件的 age 属性小于 10,左侧为数据库字段											|
|<=				|小于等于		|age<=10							|查询条件的 age 属性小于等于 10,左侧为数据库字段										|
|in				|存在在数组中	|status in ['a','b']				|查询条件的 status 是['a','b']中的一个,左侧为数据库字段								|
|!				|非				|!(status in ['a','b'])				|查询条件的 status 不是['a','b']中的任何一个											|
|&&				|与				|uid == auth.uid && age > 10		|查询记录uid属性 为 当前用户uid 并且查询条件的 age 属性大于 10							|
|&#124;&#124;	|或				|uid == auth.uid&#124;&#124;age>10	|查询记录uid属性 为 当前用户uid 或者查询条件的 age 属性大于 10							|
|test			|正则校验		|/abc/.test(content)				|查询 content字段内包含 abc 的记录。可用于替代sql中的like。还可以写更多正则实现更复杂的功能	|

这里的test方法比较强大,格式为:`正则规则.test(fieldname)`
雪洛's avatar
雪洛 已提交
252

W
wanganxp 已提交
253 254 255
具体到这个正则 `/abc/.test(content)`,类似于sql中的`content like '%abc%'`,即查询所有字段content包含abc的数据记录。

**注意编写查询条件时,除test外,均为运算符左侧为数据库字段,右侧为常量**
雪洛's avatar
雪洛 已提交
256

W
wanganxp 已提交
257
### JQL联表查询@lookup
W
wanganxp 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

`JQL`提供了更简单的联表查询方案。不需要学习join、lookup等复杂方法。

只需在db schema中,将两个表的关联字段建立映射关系,就可以把2个表当做一个虚拟表来直接查询。

比如有2个表,book表,存放书籍商品;order表存放书籍销售订单记录。

book表内有以下数据,title为书名、author为作者:

```js
{
  "_id": "1",
  "title": "西游记",
  "author": "吴承恩"
}
{
  "_id": "2",
  "title": "水浒传",
  "author": "施耐庵"
}
{
  "_id": "3",
  "title": "三国演义",
  "author": "罗贯中"
}
{
  "_id": "4",
  "title": "红楼梦",
  "author": "曹雪芹"
}
```
雪洛's avatar
雪洛 已提交
289

W
wanganxp 已提交
290
order表内有以下数据,book字段为book表的书籍_id,quantity为该订单销售了多少本书:
雪洛's avatar
雪洛 已提交
291

W
wanganxp 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
```js
{
  "book": "1",
  "quantity": 111
}
{
  "book": "2",
  "quantity": 222
}
{
  "book": "3",
  "quantity": 333
}
{
  "book": "4",
  "quantity": 444
}
{
  "book": "3",
  "quantity": 555
}
```
雪洛's avatar
雪洛 已提交
314

W
wanganxp 已提交
315
如果我们要对这2个表联表查询,在订单记录中同时显示书籍名称和作者,那么首先要建立两个表中关联字段`book`的映射关系。
雪洛's avatar
雪洛 已提交
316

W
wanganxp 已提交
317
即,在order表的db schema中,配置字段 book 的`foreignKey`,指向 book 表的 _id 字段,如下
雪洛's avatar
雪洛 已提交
318 319 320 321 322 323 324 325 326 327 328 329

```json
// order表schema
{
  "bsonType": "object",
  "required": [],
  "permission": {
    ".read": true
  },
  "properties": {
    "book": {
      "bsonType": "string",
雪洛's avatar
雪洛 已提交
330
      "foreignKey": "book._id" // 使用foreignKey表示,此字段关联book表的_id。
雪洛's avatar
雪洛 已提交
331 332 333 334 335 336
    },
    "quantity": {
      "bsonType": "int"
    }
  }
}
W
wanganxp 已提交
337
```
雪洛's avatar
雪洛 已提交
338

W
wanganxp 已提交
339 340
book表的db schema也要保持正确
```json
雪洛's avatar
雪洛 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
// book表schema
{
  "bsonType": "object",
  "required": [],
  "permission": {
    ".read": true
  },
  "properties": {
    "title": {
      "bsonType": "string"
    },
    "author": {
      "bsonType": "string"
    }
  }
}
```

W
wanganxp 已提交
359 360
schema保存至云端后,即可在前端直接查询。查询表设为order和book这2个表名后,即可自动按照一个合并虚拟表来查询,filed、where等设置均按合并虚拟表来设置。

雪洛's avatar
雪洛 已提交
361 362 363
```js
// 客户端联表查询
const db = uniCloud.database()
W
wanganxp 已提交
364 365 366 367 368 369 370 371 372
db.collection('order,book') // 注意collection方法内需要传入所有用到的表名,用逗号分隔,主表需要放在第一位
  .where('book.title == "三国演义"') // 查询order表内书名为“三国演义”的订单
  .field('book{title,author},quantity') // 这里联表查询book表返回book表内的title、book表内的author、order表内的quantity
  .get()
  .then(res => {
    console.log(res);
  }).catch(err => {
    console.error(err)
  })
雪洛's avatar
雪洛 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
  
// 上面的写法是clientDB的jql语法,如果不使用jql的话,写法会变得很长,大致如下
// 注意clientDB内联表查询需要用拼接子查询的方式(let+pipeline)
const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate
db.collection('order')
  .aggregate()
  .lookup({
    from: 'book',
    let: {
      book_id: '$book_id'
    },
    pipeline: $.pipeline()
    // 此match方法内的条件会和book表对应的权限规则进行校验,{status: 'OnSell'}会参与校验,整个expr方法转化成一个不与任何条件产生交集的特别表达式。这里如果将dbCmd.and换成dbCmd.or会校验不通过
    .match(dbCmd.expr(
        $.eq(['$_id', '$$book_id'])
      ))
    .done()
    as: 'book'
  })
  .match({
    book: {
      title: '三国演义'
    }
  })
  .end()
雪洛's avatar
雪洛 已提交
400 401 402
```


W
wanganxp 已提交
403
上述查询会返回如下结果,可以看到书籍信息被嵌入到order表的book字段下,成为子节点。同时根据where条件设置,只返回书名为三国演义的订单记录。
雪洛's avatar
雪洛 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

```js
{
	"code": "",
	"message": "",
	"data": [{
		"_id": "b8df3bd65f8f0d06018fdc250a5688bb",
		"book": [{
			"author": "罗贯中",
			"title": "三国演义"
		}],
		"quantity": 555
	}, {
		"_id": "b8df3bd65f8f0d06018fdc2315af05ec",
		"book": [{
			"author": "罗贯中",
			"title": "三国演义"
		}],
		"quantity": 333
	}]
}

```

W
wanganxp 已提交
428
关系型数据库做不到这种设计。`jql`充分利用了json文档型数据库的特点,实现了这个简化的联表查询方案。
W
wanganxp 已提交
429 430 431 432 433

不止是2个表,3个、4个表也可以通过这种方式查询。

不止js,`<uni-clientDB>`组件也支持所有`jql`功能,包括联表查询。

雪洛's avatar
雪洛 已提交
434 435 436 437
**注意**

- field参数字符串内没有冒号,{}为联表查询标志

W
wanganxp 已提交
438 439 440 441 442 443 444 445 446
### 查询列表分页

`jql`提供了更简单的分页方法,包括两种模式:

1. 滚动到底加载下一页
2. 点击页码按钮切换不同页

推荐通过`<uni-clientDB>`组件处理分页,详见:[https://uniapp.dcloud.net.cn/uniCloud/uni-clientdb-component?id=page](https://uniapp.dcloud.net.cn/uniCloud/uni-clientdb-component?id=page)

W
wanganxp 已提交
447
### 排序orderBy@orderby
雪洛's avatar
雪洛 已提交
448

W
wanganxp 已提交
449 450
传统的MongoDB的排序参数是json格式,jql支持类sql的字符串格式,书写更为简单。

雪洛's avatar
雪洛 已提交
451 452
sort方法和orderBy方法内可以传入一个字符串来指定排序规则。

W
wanganxp 已提交
453 454 455 456 457
orderBy允许进行多个字段排序,以逗号分隔。每个字段可以指定 asc(升序)、desc(降序)。

写在前面的排序字段优先级高于后面。

示例如下:
雪洛's avatar
雪洛 已提交
458 459

```js
W
wanganxp 已提交
460
orderBy('quantity asc, create_date desc') //按照quantity字段升序排序,quantity相同时按照create_date降序排序
雪洛's avatar
雪洛 已提交
461 462
// desc可以省略,上述代码和以下写法效果一致
orderBy('quantity, create_date desc')
雪洛's avatar
雪洛 已提交
463

W
wanganxp 已提交
464
// 注意不要写错成全角逗号
雪洛's avatar
雪洛 已提交
465 466
```

W
wanganxp 已提交
467
以上面的order表数据为例:
雪洛's avatar
雪洛 已提交
468

W
wanganxp 已提交
469
```js
雪洛's avatar
雪洛 已提交
470
const db = uniCloud.database()
W
wanganxp 已提交
471 472
  db.collection('order')
    .orderBy('quantity asc, create_date desc') // 按照quantity字段升序排序,quantity相同时按照create_date降序排序
雪洛's avatar
雪洛 已提交
473 474 475 476 477 478
    .get()
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
雪洛's avatar
雪洛 已提交
479 480 481 482 483 484 485 486 487 488 489 490
    
// 上述写法等价于
const db = uniCloud.database()
  db.collection('order')
    .orderBy('quantity','asc')
    .orderBy('create_date','desc')
    .get()
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
雪洛's avatar
雪洛 已提交
491 492
```

W
wanganxp 已提交
493
### 查询结果返回总数getcount@getcount
雪洛's avatar
雪洛 已提交
494

W
wanganxp 已提交
495
使用`clientDB`时可以在get方法内传入`getCount:true`来同时返回总数
雪洛's avatar
雪洛 已提交
496 497 498 499

```js
// 这以上面的order表数据为例
const db = uniCloud.database()
W
wanganxp 已提交
500
  db.collection('order')
雪洛's avatar
雪洛 已提交
501 502 503 504 505 506 507 508
    .get({
      getCount:true
    })
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
雪洛's avatar
雪洛 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
    
// 如果不使用getCount,需要再调用一次count方法来返回总数
const db = uniCloud.database()
  db.collection('order')
    .get()
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
  db.collection('order')
    .count()
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
雪洛's avatar
雪洛 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538
```

返回结果为

```js
{
	"code": "",
	"message": "",
	"data": [{
		"_id": "b8df3bd65f8f0d06018fdc250a5688bb",
		"book": "3",
		"quantity": 555
	}],
雪洛's avatar
雪洛 已提交
539
	"count": 5
雪洛's avatar
雪洛 已提交
540 541 542
}
```

W
wanganxp 已提交
543

雪洛's avatar
雪洛 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
### 查询结果时返回单条记录getone@getone

使用`clientDB`时可以在get方法内传入`getOne:true`来返回一条数据

```js
// 这以上面的book表数据为例
const db = uniCloud.database()
  db.collection('book')
    .where({
      title: '西游记'
    })
    .get({
      getOne:true
    })
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
```

返回结果为

```js
{
	"code": "",
	"message": "",
	"data": {
    "_id": "1",
    "title": "西游记",
    "author": "吴承恩"
  }
}
```
W
wanganxp 已提交
578

W
wanganxp 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
### 新增数据记录add

获取到db的表对象后,通过`add`方法新增数据记录。

`add`方法的参数为要新增的json数据,可以是单条数据、也可以是多条数据。

注意:如果是非admin账户新增数据,需要在数据库中待操作表的`db schema`中要配置permission权限,赋予create为true。

示例:

```js
// 一次插入3条数据
const db = uniCloud.database();
db.collection("table1").add(
	[{
	  name: 'Alex'
	},{
	  name: 'Ben'
	},{
	  name: 'John'
	}]
)
```

```js
// 插入1条数据,同时判断成功失败状态
const db = uniCloud.database();
db.collection("table1")
	.add({name: 'Ben'})
	.then((res) => {
		uni.showToast({
			title: '新增成功'
		})
	})
	.catch((err) => {
		uni.showModal({
			content: err.message || '新增失败',
			showCancel: false
		})
	})
	.finally(() => {
		
	})
```

**Tips**

- 云服务商选择阿里云时,若集合表不存在,调用add方法会自动创建集合表


### 删除数据记录remove
获取到db的表对象,然后指定要删除的记录,通过remove方法删除。

注意:如果是非admin账户删除数据,需要在数据库中待操作表的`db schema`中要配置permission权限,赋予delete为true。

指定要删除的记录有2种方式:

#### 方式1 通过指定文档ID删除

collection.doc(_id).remove()

删除单条记录

```js
const db = uniCloud.database();
db.collection("table1").doc("5f79fdb337d16d0001899566").remove()
```

删除该表所有数据
```js
const db = uniCloud.database();
let collection = db.collection("table1")
let res = await collection.get()
res.data.map(async(document) => {
  return await collection.doc(document.id).remove();
});
```

#### 方式2 条件查找文档后删除

collection.where().remove()

```js
// 删除字段a的值大于2的文档
try {
	await db.collection("table1").where("a>2").remove()
} catch (e) {
	uni.showModal({
		title: '提示',
		content: e.message
	})
}
```

#### 回调的res响应参数

| 字段		| 类型		| 必填	| 说明						|
| ---------	| -------	| ----	| ------------------------	|
雪洛's avatar
雪洛 已提交
677
| deleted	| Number	| 否	| 删除的记录数量			|
W
wanganxp 已提交
678 679 680 681 682

示例:判断删除成功或失败,打印删除的记录数量

```js
const db = uniCloud.database();
雪洛's avatar
雪洛 已提交
683 684 685 686 687
db.collection("table1")
  .where({
    _id: "5f79fdb337d16d0001899566"
  })
  .remove()
W
wanganxp 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
	.then((res) => {
		uni.showToast({
			title: '删除成功'
		})
		console.log("删除条数: ",res.deleted);
	}).catch((err) => {
		uni.showModal({
			content: err.message || '删除失败',
			showCancel: false
		})
	}).finally(() => {
		
	})
```

### 更新数据记录update

获取到db的表对象,然后指定要删除的记录,通过remove方法删除。

注意:如果是非admin账户修改数据,需要在数据库中待操作表的`db schema`中要配置permission权限,赋予update为true。

collection.doc().update(Object data)

**参数说明**

| 参数 | 类型   | 必填 | 说明                                     |
| ---- | ------ | ---- | ---------------------------------------- |
| data | object | 是   | 更新字段的Object,{'name': 'Ben'} _id 非必填|

**回调的res响应参数**

| 参数	| 类型	|  说明																			|
| ----	| ------|  ----------------------------------------	|
|updated| Number| 更新成功条数,数据更新前后没变化时会返回0。用法与删除数据的响应参数示例相同	|


```js
const db = uniCloud.database();
let collection = db.collection("table1")
雪洛's avatar
雪洛 已提交
727 728 729 730 731 732 733
let res = await collection.where({_id:'doc-id'})
  .update({
    name: "Hey",
    count: {
      fav: 1
    }
  });
W
wanganxp 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
```

```json
// 更新前的数据
{
  "_id": "doc-id",
  "name": "Hello",
  "count": {
    "fav": 0,
    "follow": 0
  }
}

// 更新后的数据
{
  "_id": "doc-id",
  "name": "Hey",
  "count": {
    "fav": 1,
    "follow": 0
  }
}
```

更新数组时,以数组下标作为key即可,比如以下示例将数组arr内下标为1的值修改为 uniCloud

```js
const db = uniCloud.database();
let collection = db.collection("table1")
雪洛's avatar
雪洛 已提交
763 764 765 766 767 768
let res = await collection.where({_id:'doc-id'})
  .update({
    arr: {
      1: "uniCloud"
    }
  })
W
wanganxp 已提交
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
```

```json
// 更新前
{
  "_id": "doc-id",
  "arr": ["hello", "world"]
}
// 更新后
{
  "_id": "doc-id",
  "arr": ["hello", "uniCloud"]
}
```

#### 批量更新文档

```js
const db = uniCloud.database();
let collection = db.collection("table1")
let res = await collection.where("name=='hey'").update({
  age: 18,
})
```

#### 更新数组内指定下标的元素

```js
const db = uniCloud.database();
雪洛's avatar
雪洛 已提交
798 799 800 801 802 803 804
const res = await db.collection('table1').where({_id:'1'})
  .update({
    // 更新students[1]
    ['students.' + 1]: {
      name: 'wang'
    }
  })
W
wanganxp 已提交
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
```

```json
// 更新前
{
  "_id": "1",
  "students": [
    {
      "name": "zhang"
    },
    {
      "name": "li"
    }
  ]
}

// 更新后
{
  "_id": "1",
  "students": [
    {
      "name": "zhang"
    },
    {
      "name": "wang"
    }
  ]
}
```

#### 更新数组内匹配条件的元素

**注意:只可确定数组内只会被匹配到一个的时候使用**

```js
const db = uniCloud.database();
const res = await db.collection('table1').where({
	'students.id': '001'
}).update({
  // 将students内id为001的name改为li
	'students.$.name': 'li'
})
```


```js
// 更新前
{
  "_id": "1",
  "students": [
    {
      "id": "001",
      "name": "zhang"
    },
    {
      "id": "002",
      "name": "wang"
    }
  ]
}

// 更新后
{
  "_id": "1",
  "students": [
    {
      "id": "001",
      "name": "li"
    },
    {
      "id": "002",
      "name": "wang"
    }
  ]
}
```

注意:
- 为方便控制权限,禁止前端使用set方法,一般情况下也不需要前端使用set
- 更新数据库时不可使用更新操作符`db.command.inc`
- 更新数据时键值不可使用`{'a.b.c': 1}`的形式,需要写成`{a:{b:{c:1}}}`形式(后续会对此进行优化)

雪洛's avatar
雪洛 已提交
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
### 刷新token@refreshtoken

透传uni-id自动刷新的token给客户端

**用法**

```js
const db = uniCloud.database()

function refreshToken({
  token,
  tokenExpired
}) {
  uni.setStorageSync('uni_id_token', token)
  uni.setStorageSync('uni_id_token_expired', tokenExpired)
}
// 绑定刷新token事件
db.auth.on('refreshToken', refreshToken)
// 解绑刷新token事件
db.auth.off('refreshToken', refreshToken)
```

W
wanganxp 已提交
909
## DBschema@schema
雪洛's avatar
雪洛 已提交
910

W
wanganxp 已提交
911 912 913 914 915 916 917 918 919
目前schema需要在[uniCloud web控制台](https://unicloud.dcloud.net.cn)数据表的表结构处创建/修改。

schema内可以编写数据表的权限以及字段规则校验。

web控制台还可以根据schema生成前端使用的表单校验规则,无需前端再重复做一次表单校验。(需搭配`<uni-forms>组件`[详见](https://ext.dcloud.net.cn/plugin?id=2773)

甚至可以自动生成前端用的新增、修改数据的vue页面。[详情](https://uniapp.dcloud.net.cn/uniCloud/schema?id=%e5%a6%82%e4%bd%95%e4%bd%93%e9%aa%8c)

这些工具大幅减少了开发者的开发工作量和重复劳动。
雪洛's avatar
雪洛 已提交
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989

**下面示例中使用了注释,实际使用时schema是一个标准的json文件不可使用注释。**完整属性参考[schema字段](https://uniapp.dcloud.net.cn/uniCloud/schema?id=segment)

关于如何编写permission请参考:[permission](uniCloud/database?id=permission)

```js
{
  "bsonType": "object", // 表级的类型,固定为object
  "required": ['book', 'quantity'], // 新增数据时必填字段
  "permission": { // 表级权限
    ".read": true, // 读
    ".create": false, // 新增
    ".update": false, // 更新
    ".delete": false, // 删除
  },
  "properties": { // 字段列表,注意这里是对象
    "book": { // 字段名book
      "bsonType": "string", // 字段类型
      "permission": { // 字段权限
        ".read": true, // 字段读权限
        ".write": false, // 字段写权限
      },
      "foreignKey": "book._id" // 其他表的关联字段
    },
    "quantity": {
      "bsonType": "int"
    }
  }
}
```

## permission@permission

为了更好的控制客户端行为,客户端在permission不为公有读(并非true时)时写法有以下限制:

- 不使用聚合时collection方法之后需紧跟一个where方法,这个where方法内传入的条件必须满足权限控制规则
- 使用聚合时aggregate方法之后需紧跟一个match方法,这个match方法内的条件需满足权限控制规则
- 使用lookup时只可以使用拼接子查询的写法(let+pipeline模式),做这个限制主要是因为需要确保访问需要lookup的表时也会传入查询条件,即pipeline参数里面`db.command.pipeline()`之后的match方法也需要像上一条里面的match一样限制
- 上面用于校验权限的match和where后的project和field是用来确定本次查询需要访问什么字段的(如果没有将会认为是在访问所有字段),访问的字段列表会用来确认使用那些字段权限校验。这个位置的project和field只能使用白名单模式
- 上面用于校验权限的match和where内如果有使用`db.command.expr`,那么在进行权限校验时expr方法内部的条件会被忽略,整个expr方法转化成一个不与任何条件产生交集的特别表达式,具体表现请看下面示例

实际运行时,
1. permission模块会解析前端传递的参数,分析前端操作人员的uni-id身份、要操作的数据表、字段和增删改查动作。
2. 然后从云端schema内读取数据表、字段、增删改查动作的权限配置
3. 最后根据用户身份和权限配置进行比对,以决定是否有权进行前端发起的这次数据库操作

permission规则,可以对整个表的增删改查进行控制,也可以针对字段进行控制;可以简单的配置true/false,也可以配置更具体的规则

比如permission内规定doc.a > 1,那么查询条件里面就必须有a且条件内的a也满足a>1,`{a:2}``{a:db.command.gt(3)}`都是满足条件的查询。

**schema内permission配置示例**

```js
// order表schema
{
  "bsonType": "object", // 表级的类型,固定为object
  "required": ['book', 'quantity'], // 新增数据时必填字段
  "permission": { // 表级权限
    ".read": "doc.uid == auth.uid", // 每个用户只能读取用户自己的数据。前提是要操作的数据doc,里面有一个字段存放了uid,即uni-id的用户id。(不配置时等同于false)
    ".create": false, // 禁止新增数据记录(不配置时等同于false)
    ".update": false, // 禁止更新数据(不配置时等同于false)
    ".delete": false, // 禁止删除数据(不配置时等同于false)
  },
  "properties": { // 字段列表,注意这里是对象
    "secret_field": { // 字段名
      "bsonType": "string", // 字段类型
      "permission": { // 字段权限
        ".read": false, // 禁止读取secret_field字段的数据
        ".write": false // 禁止写入(包括更新和新增)secret_field字段的数据,父级节点存在false时这里可以不配
      }
雪洛's avatar
雪洛 已提交
990 991 992 993 994 995 996 997
    },
    "uid":{
      "bsonType": "string", // 字段类型
      "foreignKey": "uni-id-users._id"
    },
    "book_id": {
      "bsonType": "string", // 字段类型
      "foreignKey": "book._id"
雪洛's avatar
雪洛 已提交
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    }
  }
}
```

```js
// book表schema
{
  "bsonType": "object",
  "required": ['book', 'quantity'], // 新增数据时必填字段
  "permission": { // 表级权限
    ".read": "doc.status == 'OnSell'" // 允许所有人读取状态是OnSell的数据
  },
  "properties": { // 字段列表,注意这里是对象
雪洛's avatar
雪洛 已提交
1012 1013 1014 1015 1016 1017
    "title": {
      "bsonType": "string"
    },
    "author": {
      "bsonType": "string"
    },
雪洛's avatar
雪洛 已提交
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    "secret_field": { // 字段名
      "bsonType": "string", // 字段类型
      "permission": { // 字段权限
        ".read": false, // 禁止读取secret_field字段的数据
        ".write": false // 禁止写入(包括更新和新增)secret_field字段的数据
      }
    }
  }
}
```

**请求示例**

```js
const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate
db.collection('order')
雪洛's avatar
雪洛 已提交
1036 1037 1038
  .where('uid == $env.uid && book_id.status == "OnSell"')
  .field('uid,book_id{title,author}')
  .get()
雪洛's avatar
雪洛 已提交
1039 1040
```

雪洛's avatar
雪洛 已提交
1041
**权限规则变量**
雪洛's avatar
雪洛 已提交
1042

W
wanganxp 已提交
1043 1044 1045
|变量名			|说明																																						|
|:-:			|:-:																																						|
|auth.uid		|用户id																																						|
W
wanganxp 已提交
1046
|auth.role		|用户角色数组,参考[uni-id 角色权限](/uniCloud/uni-id?id=rbac),注意`admin``clientDB`内置的角色,如果用户角色列表里包含`admin`则认为此用户有完全数据访问权限|
W
wanganxp 已提交
1047 1048 1049 1050
|auth.permission|用户权限数组,参考[uni-id 角色权限](/uniCloud/uni-id?id=rbac)																								|
|doc			|记录内容,用于匹配记录内容/查询条件(需要注意的是,规则内的doc对象并不是直接去校验存在于数据库的数据,而是校验客户端的查询条件)							|
|now			|当前时间戳(单位:毫秒),时间戳可以进行额外运算,如doc.publish\_date > now - 60000表示publish\_date在最近一分钟											|
|action			|当前客户端指定的action																																		|
雪洛's avatar
雪洛 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

permission为对数据的操作权限,如果要封装业务权限,可以在uni-id的业务权限表里进行配置。业务权限进一步可组装为角色。然后每个具体的uni-id用户可以被赋予某个角色。

如果在uni-id里定义了业务权限和角色,也可以在permission中通过auth.permission和auth.role来使用,以实现更灵活的配置定义。

**权限规则内可以使用的运算符**

|运算符				|说明					|示例																		|示例解释(集合查询)																										|
|:-:					|:-:					|:-:																		|:-:																																	|
|==						|等于					|auth.uid == 'abc'											|用户id为abc																													|
|!=						|不等于				|auth.uid != 'abc'											|用户id不为abc																												|
|>						|大于					|doc.age>10															|查询条件的 age 属性大于 10																						|
|>=						|大于等于			|doc.age>=10														|查询条件的 age 属性大于等于 10																				|
|<						|小于					|doc.age<10															|查询条件的 age 属性小于 10																						|
|<=						|小于等于			|doc.age<=10														|查询条件的 age 属性小于等于 10																				|
|in						|存在在数组中	|doc.status in ['a','b']								|查询条件的 status 是['a','b']中的一个,数组中所有元素类型需一致			|
|!						|非						|!(doc.status in ['a','b'])							|查询条件的 status 不是['a','b']中的任何一个,数组中所有元素类型需一致|
|&&						|与						|auth.uid == 'abc' && doc.age>10				|用户id 为 abc 并且查询条件的 age 属性大于 10													|
|&#124;&#124;	|或						|auth.uid == 'abc'&#124;&#124;doc.age>10|用户Id为abc或者查询条件的 age 属性大于 10														|

**权限规则内可以使用的方法**

目前权限规则内仅可使用get方法,作用是根据id获取数据库中的数据。get方法接收一个字符串作为参数字符串形式为`database.表名.记录ID`

用法示例: 

```js
"get(`database.shop.${doc.shop_id}`).owner == auth.uid"
```

使用get方法时需要注意get方法的参数必须是唯一确定值,以上述示例为例

```js
// 可以使用的查询条件,此条件内doc.shop_id只能是'123123'
db.collection('street').where({
  shop_id: '123123'
}).get()

// 不可使用的查询条件,此条件内doc.shop_id可能是'123123'也可能是'456456'
const dbCmd = db.command
db.collection('street').where(dbCmd.or([
  {
    shop_id: '123123'
  },
  {
    shop_id: '456456'
  }
])).get()
```

雪洛's avatar
雪洛 已提交
1101
## action@action
雪洛's avatar
雪洛 已提交
1102

W
wanganxp 已提交
1103 1104 1105 1106 1107
action的作用是在执行前端发起的数据库操作时,额外触发一段云函数逻辑。它是一个可选模块。

当一个前端操作数据库的方式不能完全满足需求,仍然同时需要在云端再执行一些云函数时,就在前端发起数据库操作时,通过db.action("someactionname")方式要求云端同时执行这个叫someactionname的action。还可以在权限规则内指定某些操作必须使用指定的action,比如`"action in ['action-a','action-b']"`,来达到更灵活的权限控制。

如果使用`<uni-clientdb>组件`,该组件也有action属性,设置action="someactionname"即可。
雪洛's avatar
雪洛 已提交
1108

雪洛's avatar
雪洛 已提交
1109 1110 1111 1112
**新建actions**

![新建actions](https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/b6846d00-1460-11eb-b997-9918a5dda011.jpg)

W
wanganxp 已提交
1113
每个action在uni-clientDB-actions目录下存放一个以action名称命名的js文件。
雪洛's avatar
雪洛 已提交
1114

W
wanganxp 已提交
1115
在这个js文件的代码里,包括before和after两部分。
雪洛's avatar
雪洛 已提交
1116 1117

- before部分的常用用途:
W
wanganxp 已提交
1118
	* 对前端传入的数据进行二次处理
雪洛's avatar
雪洛 已提交
1119 1120 1121
	* 在此处开启数据库事务,万一操作数据库失败,可以在after里回滚
	
- after部分的常用用途:
W
wanganxp 已提交
1122
	* 对将要返回给前端的数据进行二次处理
雪洛's avatar
雪洛 已提交
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
	* 也可以在此处处理错误,回滚数据库事务
	* 对数据库进行二次操作,比如前端查询一篇文章详情后,在此处对文章的阅读数+1。因为permission里定义,一般是要禁止前端操作文章的阅读数字段的,此时就应该通过action,在云函数里对阅读数+1

示例:

```js
// 客户端发起请求,给todo表新增一行数据,同时指定action为add-todo
const db = uniCloud.database()
db.action('add-todo')
  .collection('todo')
  .add({
    title: 'todo title'
  })
  .then(res => {
    console.log(res)
  }).catch(err => {
    console.error(err)
  })
```

```js
W
wanganxp 已提交
1144
// 一个action文件示例 uni-clientDB-actions/add-todo.js
雪洛's avatar
雪洛 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
module.exports = {
  // 在数据库操作之前执行
  before: async(state,event)=>{
    // state为当前clientDB操作状态其格式见下方说明
    // event为传入云函数的event对象
    
    // before内可以操作state上的newData对象对数据进行修改,比如:
    state.newData.create_time = Date.now()
    // 指定插入或修改的数据内的create_time为Date.now()
    // 执行了此操作之后实际插入的数据会变成 {title: 'todo title', create_time: xxxx}
W
wanganxp 已提交
1155
    // 实际上,这个场景,有更简单的实现方案:在db schema内配置defaultValue或者forceDefaultValue,即可自动处理新增记录使用当前服务器时间
雪洛's avatar
雪洛 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
  },
  // 在数据库操作之后执行
  after:async (state,event,error,result)=>{
    // state为当前clientDB操作状态其格式见下方说明
    // event为传入云函数的event对象
    // error为执行操作的错误对象,如果没有错误error的值为null
    // result为执行command返回的结果
    
    if(error) {
      throw error
    }
    
W
wanganxp 已提交
1168
    // after内可以对result进行额外处理并返回
雪洛's avatar
雪洛 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    result.msg = 'hello'
    return result
  }
}
```

**state**参数说明

```js
// state参数格式如下
{
  command: {
    // getMethod('where') 获取所有的where方法,返回结果为[{$method:'where',$param: [{a:1}]}]
    getMethod,
    // getMethod({name:'where',index: 0}) 获取第1个where方法的参数,结果为数组形式,例:[{a:1}]
    getParam,
    // setParam({name:'where',index: 0, param: [{a:1}]}) 设置第1个where方法的参数,调用之后where方法实际形式为:where({a:1})
    setParam
  },
  // 需要注意的是clientDB可能尚未获取用户信息,如果权限规则内没使用auth对象且数据库指令里面没使用db.env.uid则clientDB不会自动取获取用户信息
  auth: {
    uid, // 用户ID,如果未获取或者获取失败uid值为null
    role, // 通过uni-id获取的用户角色,需要使用1.1.9以上版本的uni-id,如果未获取或者获取失败role值为[]
    permission // 通过uni-id获取的用户权限,需要使用1.1.9以上版本的uni-id,如果未获取或者获取失败permission值为[],注意登录时传入needPermission才可以获取permission,请参考 https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=rbac
  },
  // 事务对象,如果需要用到事务可以在action的before内使用state.transaction = await db.startTransaction()传入
  transaction,
  // 更新或新增的数据
  newData,
  // 访问的集合
  collection,
  // 操作类型,可能的值'read'、'create'、'update'、'delete'
  type
}
```