uniCloud云开发----4、uniCloud云开发进阶使用方法

前言

之前介绍了unicloud的基本使用方法,本篇讲解一些unicloud的便捷性的使用方法和数据库的操作方式

1、云对象的importObject的创建和使用

(1)创建云对象

在这里插入图片描述
在这里插入图片描述

(2)编辑云对象

// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程:https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const db = uniCloud.database()
module.exports = {
    
    
	_before: function () {
    
     // 通用预处理器

	},
	async get(name){
    
    
		return await db.collection('users').where({
    
    
			name:new RegExp(name, 'ig')
		}).get()
	},
	add:async ()=>{
    
    
		await db.collection('users').add({
    
    
			name:'姓名',
			age:18
		})
	}
}

(3)在.vue文件中调用云对象

const cloudGetList = uniCloud.importObject("cloudGetList")

(4)在.vue文件中调用方法

get(id, num, name) {
    
    
	cloudGetList.get('111').then(res=>{
    
    
		this.listArr = res.data
		console.log(res.data)
	})
},

在这里插入图片描述

2、客户端直接连接数据库

(1)直接在客户端引用

在这里插入图片描述

(2)会出线这样的报错

在这里插入图片描述

(3)解决报错–将数据库下载到本地,可以在这里创建和上传到云端

在这里插入图片描述

(4)报错变为 未能获取当前用户信息:当前用户为匿名身份

在这里插入图片描述

(5)解决为获取当前用户信息错误(去数据库表的json中配置权限)

在这里插入图片描述
在这里插入图片描述

3、配置数据库的权限json

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

{
    
    
	"bsonType": "object",
	"required": [],
	"permission": {
    
    
		"read": true,
		"create": true,
		"update": false,
		"delete": false
	},
	"properties": {
    
    
		"_id": {
    
    
			"description": "ID,系统自动生成"
		},
		"title":{
    
    
			"bsonType": "string", 
			"title":"标题",  
			"description":"数据的标题"
		},
		"file":{
    
    
			"title":"图片链接",  
			"description":"图片链接",
			"errorMessage":"图片链接必填"
		},
		"time":{
    
    
			"bsonType": "timestamp",
			"title":"发布时间",
			"description":"发布时间",
			"defaultValue":{
    
    
				 "$env": "now"
			}
		}
	}
}

4、官网配置好的数据库表

在这里插入图片描述

5、通过jql语法使用筛选

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

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

db.collection('list')
  .where('name == "hello-uni-app"')
  .get()
  .then((res)=>{
    
    
    // res 为数据库查询结果
  }).catch((err)=>{
    
    
    // err.message 错误信息
    // err.code 错误码
  })

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_50207524/article/details/128499802