unicloud云开发进阶5-openDB预置数据表的结构

129 阅读1分钟

把报错信息显示在前端

前一节是把报错信息展示在控制台,这不合理,需要在页面中展示出来提醒用户 使用catch方法获取到报错信息,然后使用uni.showtoast 弹出一个弹窗展示

<script>
  const db=uniCloud.database();
	export default {
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {
      this.getData();
		},
		methods: {
      addClick(){
        db.collection("cloudDemo").add({  
          title:"aaabbb"
        }).then(res=>{
          // console.log(res);
          uni.showToast({
            title:"添加成功"
          })
        }).catch(err=>{
          // console.log(err.message);
          uni.showToast({
            title:err.message,
            icon:'none'
          })
        })
      }
	}
}
</script>

image.png

trim属性 去掉前后空格

在add方法中提交title,在值的前后添加空格(添加多个空格会变成一个空格),提交后,在数据库中title这一个字段的值就是前后都有空格的

image.png

<script>
  const db=uniCloud.database();
	export default {
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {
      this.getData();
		},
		methods: {
      addClick(){
        db.collection("cloudDemo").add({  
          title:"  aaabbb  "
        }).then(res=>{
          // console.log(res);
          uni.showToast({
            title:"添加成功"
          })
        }).catch(err=>{
          // console.log(err.message);
          uni.showToast({
            title:err.message,
            icon:'none'
          })
        })
      }
	}
}
</script>

去掉前后空白

    "title":{
      "bsonType": "string",
      // 这个title是属性,上面的title是字段名
      "title": "文章标题",
      // 说明,开发者使用
      "description": "文章的标题",
      // 修改报错信息
      "errorMessage":"标题必须填写",
      // 去掉前后的空白
      "trim": "both"
    },

opendb

openDB是unicloud提供的一些常用的数据结构,有用户管理、电商系统等 这里使用其中的新闻系统 opendb-news,在文档中有一个gitee地址,代码就在这里面,有几十个常用数据结构

image.png 打开这个表结构 在collection.json文件中,就是一个dbScheam结构

image.png

这里可以看到三个必填字段,id、title和内容 然后读的操作是

{

  "schema": {

    "bsonType": "object",

    "required": ["user_id", "title", "content"],

    "permission": {

      "read": "doc.user_id == auth.uid && doc.article_status == 0 || doc.article_status == 1",

      "create": "auth.uid != null",

      "update": "doc.user_id == auth.uid",

      "delete": "doc.user_id == auth.uid"

    },