uniCloud advanced (1. Proficient in DB Schema table structure)


Preface

Proficient in DB Schema table structure


1. Table structure DB Schema

Right click on the database and create a new DB Schema
Insert image description here

Schema validation rules


	"bsonType": "object",
	"required": ["title"],//必填
	"permission": {
    
    
		"read":  true,//检验keyid
		"create": "atuo.uid != null",//校验用户登录
		"update": false,
		"delete": false
	},
	"properties": {
    
    //数据库数据验证 字段
		"_id": {
    
    
			"description": "ID,系统自动生成"
		},
		"title":{
    
    
			  "bsonType": "string",
			  "title": "文章标题",
			  "description": "文章的标题",
			  "errorMessage":"标题必须填写",
			  "trim": "both"
		},
		"userid":{
    
    
			"bsonType": "string",
			"title": "用户id",
			"foreignKey": "uni-id-users._id",
			"defaultValue":{
    
    //默认值now/时间戳, clientIP/客户端ip  
			用户id uid 
				"$env":"uid"
			}
		}
	}
}

properties field properties

The field list in properties, each field has many properties that can be set, as follows:

Attribute classification Attributes type describe
basic bsonType any Field type, such as json object, string, number, bool value, date, timestamp, see the table below for details of bsonType available types
basic arrayType String Array item type, valid when bsonType="array", supported by HBuilderX 3.1.0+, see the following table for available types of arrayType
basic title string Title, used by developers for maintenance. When schema2code generates the front-end form code, it is used by default for the label in front of the form item.
basic description string Description, used by developers for maintenance. When generating the front-end form code, if the field is not set to componentForEdit and the field is rendered as input, the placehold of the input will default to this description.
basic defaultValue string、Object default value
basic forceDefaultValue string、Object Mandatory default value, which cannot be modified by clientDB code, is often used to store fixed values ​​such as user id, time, client ip, etc. Please refer to the defaultValue in the following table for details.
Value range check required array Is it required? Supports filling in required subordinate field names. required can appear in the table-level description, specifying which fields of the table are required. It can also appear in a certain field. If the field is a json object, you can describe which fields in the json are required. See example below for details
Value range check enum Array Field value enumeration range, there must be at least one element in the array, and each element in the array is unique.
Value range check enumType String Field value enumeration type, optional value tree. When set to tree, it means that the data in the enum is a tree structure. At this time schema2code can generate multi-level cascade selection components
Value range check fileMediaType String File type, valid when bsonType="file", optional value all
Value range check fileExtName String File extension filtering, valid when bsonType="file", multiple file extensions are separated by ",", for example: jpg, png, supported by HBuilderX 3.1.0+
Value range check maximum number If bsonType is a number, the maximum acceptable value
Value range check exclusiveMaximum boolean Whether to exclude maximum
Value range check minimum number If bsonType is a number, the minimum acceptable value
Value range check exclusiveMinimum boolean Whether to exclude minimum
Value range check minLength number Limit the minimum length of a string or array
Value range check maxLength number Limit the maximum length of a string or array
Value range check trim String Remove whitespace characters, support none
Value range check format ‘url’、‘email’ Data format, data that does not conform to the format cannot be stored in the database. Currently only 'url' and 'email' are supported, other formats will be expanded in the future
Value range check pattern String Regular expression. For example, if it is set to the regular expression of a mobile phone number, if it does not match the regular expression, the verification will fail and cannot be stored in the database.
Value range check validateFunction string Extended verification function name
Permission verification permission Object Database permissions control which roles can read/write what data, control tables and fields, and set where conditions. See details below
error return errorMessage string、Object When data is written or updated, the error message returned after failing to verify the validity of the data
connection relation foreignKey String Related fields. Indicates that the original definition of the field points to a field in another table, and the format of the value is table name.Field name. For example, the order user uid field of the order table points to the _id field of the uni-id-users table, then the value is uni -id-users._id. After the associated fields are defined, they can be used for joint table queries. Virtual joint tables are synthesized through the associated fields, which greatly simplifies the complexity of joint table queries.
connection relation parentKey String Parent fields in the same data table. For details, refer to: Tree Data Query
schema2code label string Field title. When schema2code generates front-end code, it renders the label title in front of the form item. If left blank, the title attribute will be used. Suitable for situations where the title cannot be displayed in front of the form item
schema2code group string group id. When schema2code generates front-end code, form items corresponding to multiple fields can be combined and displayed in a uni-group component.
schema2code order int Form item sorting number. When schema2code generates front-end code, the form items are arranged from top to bottom in the order of fields in the schema by default. However, if order is specified, the order will be sorted in the order specified by order. If the form item is included in a uni-group, the same group will be sorted by order.
schema2code component Object、Array When schema2code generates front-end code, what component is used to render this form item. Deprecated. Please use componentForEdit and componentForShow below
schema2code componentForEdit Object、Array HBuilderX 3.1.0+, when generating front-end editing page files (add.vue, edit.vue), what component is used to render this form item. For example, use the input input box.
schema2code componentForShow Object、Array HBuilderX 3.1.0+, when generating the front-end display page (list.vue, detail.vue), what component is used for rendering. For example, use uni-dateformat to format dates.

required form required fields, input format

bsonType

  • bool: Boolean value, true|false
  • string: string
  • password:一种特殊的string。这类字段不会通过clientDB传递给前端,所有用户都不能通过clientDB读写,即使是admin管理员。uni-id-user表有示例
  • int:整数
  • double:精度数。由于浮点精度问题,慎用
  • object:json对象。地理位置也属于object
  • file:一种特殊的object,固定格式存放云存储文件的信息。不直接存储文件,而是一个json object,包括云存储文件的名称、路径、文件体积等信息。(HBuilderX 3.1.0+ )
  • array:数组
  • timestamp:时间戳
  • date:日期

新增照片字段

"photo": {
    
    
        "bsonType": "file",
        "title": "照片",
        "fileMediaType": "image", // 可选值 all|image|video 默认值为all,表示所有文件,image表示图片类型文件,video表示视频类型文件
        "fileExtName": "jpg,png", // 扩展名过滤,多个用 , 分割
      }

arrayType 指定数组每一项的类型

bsonType为array时使用

"images": {
    
    
        "bsonType": "array",
        "arrayType": "file",
        "title": "照片",
		"multiple": true, // 允许选择多张图片,schema2code生效
        "fileMediaType": "image", // 可选值 all|image|video 默认值为all,表示所有文件,image表示图片类型文件,video表示视频类型文件
        "fileExtName": "jpg,png", // 扩展名过滤,多个用 , 分割
        "maxLength": 3 // 限制最大数量
      }

defaultValue/forceDefaultValue 默认值

  • defaultValue普通默认值
  • forceDefaultValue 强制默认值,不可修改
"defaultValue": {
    
    
  "$env": "now"
}

预置变量$env取值:

变量 说明
now 当前服务器时间戳
clientIP 当前客户端IP
uid 当前用户Id,基于uni-id。如果当前用户未登录或登录状态无效会报错

foreignKey 关联数据表

foreignKey 前半部分是另一张表的表名,中间用.分割,后半部分是另一张表的字段名
作用:联表查询

 "user_id": {
    
    
	"bsonType": "string",
	"description": "文章作者ID",
	"foreignKey": "uni-id-users._id",
	"defaultValue": {
    
    
	  "$env": "uid"
	}
  },

parentKey树形表

  • 形式化父子关系,实现tree查询
  • 使用parentKey描述了字段父子关系后,就可以通过JQL的getTree方便的做tree查询
"parent_id": {
    
    
      "bsonType": "string",
      "description": "父id",
      "parentKey": "_id", // 指定父子关系为:如果数据库记录A的_id和数据库记录B的parent_id相等,则A是B的父级。
    },

validator 字段值域规则 required

  • required填写后该字段不可为空
  • 当required没填写,则进行name下的规则验证,name长度不能小于2
{
    
    
  "bsonType": "object",
  "required": ["name"],
  "properties": {
    
    
    "name": {
    
    
      "bsonType": "string",
      "title": "姓名",
      "minLength": 2,
      "errorMessage"{
    
    
         "required": "{title}不能为空",
        "minLength": "{title}不能小于 {minLength} 个字符"
       }
    }
  }
}

format 验证url网址

  • 仅对string类型字段生效。
  • http:// | https:// | ftp:// 开头, // 后必须包含一个 .(localhost除外)
 "properties": {
    
    
    "email": {
    
    
      "bsonType": "string",
      "title": "邮箱",
      "format": "email",
      "errorMessage": {
    
    
        "required": "{title}不能为空",
        "format": "{title}格式无效"
      }
    }
  }

pattern正则表达式

正则验证
例:验证手机号 “pattern”: “^\+?[0-9-]{3,20}$”

"properties": {
    
    
    "name": {
    
    
      "bsonType": "string",
      "title": "姓名",
      "pattern": "",
      "errorMessage": {
    
    
        "required": "{title}不能为空",
        "pattern": "{title}格式无效"
      }
    }
  }

enum枚举控制值域

设置enum枚举属性后传入的值只能是enum有的值,否则报错,无法插入或更新数据

enum格式之支持描述的复杂数组

 "gender": {
    
    
      "bsonType": "array",
      "title": "性别",
      "description": "用户性别:0 未知 1 男性 2 女性",
      "enum": [0,1,2]
    }

enum格式之支持描述的复杂数组

"enum": [
			{
    
    
				"text": "未知",
				"value": 0
			},
	]

enum格式之数据表查询

 "enum": {
    
    
        "collection": "opendb-nation-china",
        "orderby": "first_letter asc",
        "field": "name as value, name as text"
      }

enum格式之数据表查询之tree型数据
代表enum里的数据为树形结构,在schema2code时,可自动生成多级级联选择组件

"city_id": {
    
    
        "bsonType": "string",
        "title": "地址",
        "description": "城市编码",
        "foreignKey": "opendb-city-china.code",
        "enumType": "tree",
        "enum": {
    
    
          "collection": "opendb-city-china",
          "orderby": "value asc",
          "field": "code as value, name as text"
        }
      }

trim 去除首尾空白字符

描述
none 不处理。默认为none
both 从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR 等)
start 从字符串的开头移除空白字符
end 从一个字符串的末端移除空白字符

fieldRules字段间校验

验证字段之间的关系逻辑

{
    
    
  "bsonType": "object",
  "required": ["title","create_date"],
  "fieldRules": [{
    
    
    "rule": "end_date == null || end_date != null && create_date < end_date",
    "errorMessage": "结束时间需大于创建时间"
  }],
  "properties": {
    
    
    "title": {
    
    
      "bsonType": "string",
      "title": "标题"
    },
    "create_date": {
    
    
      "bsonType": "timestamp",
      "title": "创建时间",
      "forceDefaultValue": {
    
    
        "$env": "now"
      }
    },
    "end_date": {
    
    
      "bsonType": "timestamp",
      "title": "结束时间"
    }
  }
}

validateFunction扩展校验函数

  1. 在左侧项目管理器选择工程,对其下的uniCloud目录点右键,选择创建database目录(如果已有该目录则忽略本步骤)

  2. 在第一步创建的database目录右键选择创建数据库扩展校验函数目录

  3. 在第二步创建的validateFunction目录右键选择新建数据库扩展校验函数

  • validateFunction 类型为字符串时,云端和客户端同时生效

扩展校验函数

// 扩展校验函数示例
module.exports = function (rule, value, data, callback) {
    
    
  // rule  当前规则
  // value 当前规则校验数据
  // data  全部校验数据
  // callback 可选,一般用于自定义 errorMessage,如果执行了callback return 值无效,callback 传入的 message 将替换 errorMessage
  // callback('message') 传入错误消息时校验不通过
  // callback() 无参时通过
  // 注意 callback 不支持异步调用,异步请使用 Promise/await/async
  return value.length < 10
}

// 异步校验 Promise
module.exports = function (rule, value, data) {
    
    
  return new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      if (value > 10) {
    
    
        // 校验通过
        resolve()
      } else {
    
    
        // 校验失败
        resolve('error') // 等于 reject(new Error('error'))
        // reject(new Error('error'))
      }
    }, 3000);
  })
}

// 异步校验 await/async
module.exports = async function (rule, value, data) {
    
    
  let result = await uni.request({
    
    ...})
  if (result > 10) {
    
    
    // 校验通过
    return true
  } else {
    
    
    // 校验失败
    return 'error message'
  }
}


表引用

{
    
    
  "bsonType": "object",
  "required": ["name"],
  "properties": {
    
    
    "name": {
    
    
      "bsonType": "string",
      "title": "姓名",
      "validateFunction": "checkabc",
      "errorMessage": {
    
    
        "required": "{title}不能为空"
      }
    }
  }
}

// "validateFunction": {
    
    
//          "name": "checkabc", // 扩展校验函数名
//          "client": false //如果不配置默认是 true
 //     },

如果配置了 “client”: false 客户端也可以在生成的代码中改为自己的校验函数,此时客户端的校验仍然生效,客户端对应的校验文件目录为 js_sdk/validator/collection, collection为表名,非固定值

当使用schema2code生成前端页面,那么写扩展校验函数需要多一层注意。
比如调用了uniCloud.httpclient这样在前端并不存在的API时,前端的表单校验会出错。
此时就需要在扩展校验函数中多写一个if判断,避免undefined的问题。

if (uniCloud.httpclient) {
    
    
	console.log("此处运行在云函数环境里。前端没有这个API");
}
// 或者另一种写法
if (uni) {
    
    
	console.log("此处运行在前端环境里。云函数没有uni对象,除非你在validateFunction里自己定义了这个对象");
}

errorMessage自定义错误提示

数据不符合schema配置的规范时,无法入库,此时会报错

"errorMessage": {
    
    
        "required": "{title}必填",
        "minLength": "{title}不能小于{minLength}个字符",
        "maxLength": "{title}不能大于{maxLength}个字符"
      },


 "errorMessage": "{title}应该大于 {minimum} 岁,小于 {maximum} 岁"

permission 数据权限系统

  1. 对数据的指定
  • 可以对整个表进行增删改查或计数控制

  • 可以针对字段进行读写控制

  • 可以配置具体的where规则,对指定的数据记录进行删改查控制

  • 默认自带一个特殊数据的描述,就是当前请求计划操作的数据(doc),后面会详解用法

  1. 对角色的指定
  • 未登录,即游客都可以操作数据
  • 当前已登录用户(auth.uid)
  • uni-id定义的其他角色
  • 开发者可以在uni-id中自定义各种角色,比如部门管理员,然后在DB Schema的permission中配置其可操作的数据。

注意:如果登录用户是uni-id的admin角色,即超级管理员,则不受DB Schema的配置限制的,admin角色拥有对所有数据的读写权限。

表级权限控制

"permission": {
    
    
    "read": true, // 任何用户都可以读
    "create": false, // 禁止新增数据记录(admin权限用户不受限)
    "update": false, // 禁止更新数据(admin权限用户不受限)
    "delete": false, // 禁止删除数据(admin权限用户不受限)
    "count": false // 禁止查询数据条数(admin权限用户不受限),新增于HBuilderX 3.1.0
  },

字段级权限控制

如果字段的bsonType配置为password,则clientDB完全不可操作此字段(即使是admin用户也不可以在客户端读写)。

 "age": {
    
    
      "bsonType": "number",
      "title": "年龄",
      "permission": {
    
    
        "read": false, // 禁止读取 age 字段的数据(admin权限用户不受限)
        "write": false // 禁止写入 age 字段的数据(admin权限用户不受限)
      }
    }

指定数据集权限控制

"permission": {
    
    
    "read": "doc.status==true", // 任何用户都可以读status字段的值为true的记录,其他记录不可读
    "create": false, // 禁止新增数据记录(admin权限用户不受限)
    "update": false, // 禁止更新数据(admin权限用户不受限)
    "delete": false // 禁止删除数据(admin权限用户不受限)
  },

权限规则的变量和运算符

变量名 说明
auth.uid 用户id
auth.role 用户角色数组,参考uni-id 角色权限,注意admin为内置的角色,如果用户角色列表里包含admin则认为此用户有完全数据访问权限
auth.permission 用户权限数组,参考uni-id 角色权限
doc 数据库中的目标数据记录,用于匹配记录内容/查询条件
now 当前服务器时间戳(单位:毫秒),时间戳可以进行额外运算,如doc.publish_date > now - 60000表示publish_date在最近一分钟
action The data operation request also specifies the uni-clientDB-action. The data operation used to specify the front end must be accompanied by the execution of an action cloud function. If the action is not triggered, the permission verification will fail.

Operators that can be used within permission rules

Operators are similar to js

operator illustrate Example Example explanation (collection query)
== equal auth.uid == ‘abc’ The user id is abc
!= not equal to auth.uid != null The user must be logged in
> more than the doc.age>10 The age attribute of the target data is greater than 10
>= greater or equal to doc.age>=10 The age attribute of the target data is greater than or equal to 10
< less than doc.age<10 The age attribute of the target data is less than 10
<= less than or equal to doc.age<=10 The age attribute of the target data is less than or equal to 10
in exists in the array doc.status in [‘a’,‘b’] The status of the target data is one of ['a', 'b'], and all elements in the array must be of the same type.
! No !(doc.status in [‘a’,‘b’]) The status of the target data is not any one of ['a', 'b'], and all elements in the array must be of the same type.
&& and auth.uid == ‘abc’ && doc.age>10 The user id is abc and the age attribute of the target data is greater than 10
|| or auth.uid == ‘abc’ doc.age>10 The user ID is abc or the age attribute of the target data is greater than 10

Summarize

In-depth knowledge of database table structure

Guess you like

Origin blog.csdn.net/yang20000222/article/details/130903287