uniCloud 云对象使用

云函数与微信云函数基本一致
参考:https://blog.csdn.net/weixin_43512977/article/details/124579654
项目:https://blog.csdn.net/weixin_43512977/article/details/124739811

云对象 article

参数与微信云有略微差别
官方文档

// 快捷键 cdb 
const db = uniCloud.database()
const _ = db.command
const uniID = require('uni-id')
module.exports = {
	// 预处理 _before 一般用于拦截器、统一的身份验证、参数校验等。
	_before() {
		// 获取客户端信息
		const clientInfo = this.getClientInfo()
		this.uniID = uniID.createInstance({ // 创建uni-id实例,其上方法同uniID
			clientInfo
		})
		// 获取 token  缓存字段必须是 uni_id_token
		const token = this.getUniIdToken()
		// 获取方法名
		const methodName = this.getMethodName()
		// 获取参数 []
		const params = this.getParams()
	},
	// 后处理 _after 用来再加工处理本次调用方法的返回结果或者抛出的错误
	// 可以不写。如果写了 _after 那么就要 return result 否则接收不到信息
	_after(error, result) {
		console.log('error', error);
		console.log('result', result);
		if (error) {
			throw error // 如果方法抛出错误,也直接抛出不处理
		}
		return result
	},
	// 添加
	async add() {
		try {
			await db.collection('test').add({
				name: 'zs',
				age: 25
			})
		} catch (e) {
			console.log(e);
		}
	},
	// 查
	async get() {
		try {
			const res = await db.collection('test').doc('627be34fc2b3040001c20f43').get()
			console.log(res);
		} catch (e) {
			//TODO handle the exception
		}
	},
	// 更新 无则创建
	async update() {
		try {
			// const res = await db.collection('test').doc('627be34fc2b3040001c20f43').update({
			// 	age: 28,
			// 	sex: 2
			// })
			// 更新并返回新的值
			const res = await db.collection('test').doc('627be34fc2b3040001c20f43').updateAndReturn({
				age: 28,
				sex: 0
			})
			console.log(28, res);
		} catch (e) {
			//TODO handle the exception
		}
	},

	// 删除
	async remove() {
		try {
			await db.collection('test').doc('627be3172319ec00015e5a07').remove()
		} catch (e) {
			//TODO handle the exception
		}
	}

}

使用

从HBuilderX 3.4.6起,调用云对象的方法时,默认会自动显示交互/提示界面。(当errCode != 0 时触发)

// 导入云对象
const article = uniCloud.importObject('article', {
	// customUI: true, // 取消自动展示的交互提示界面
	loadingOptions: { // loading相关配置
		title: '加载中...', // 显示的loading内的提示文字。默认值为:加载中...
		mask: true // 是否使用透明遮罩,配置为true时不可点击页面其他内容。默认值为:true
	},
	errorOptions: { // 错误界面相关配置
		type: 'modal', // 错误信息展示方式,可取值:modal(弹框,默认)、toast(toast消息框)。默认值为:modal
		retry: false // 是否展示重试按钮,仅在type为modal时生效。用户点击重试按钮时将重新请求调用的方法,默认为false
	}
})
// 调用
article.get()
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值