云开发模式
官方文档:什么是云开发模式
介绍:开发者可以使用云开发开发微信小程序、小游戏,无需搭建服务器,即可使用云端能力。云开发为开发者提供完整的原生云端支持和微信服务支持,弱化后端和运维概念,无需搭建服务器,使用平台提供的 API 进行核心业务开发,即可实现快速上线和迭代,同时这一能力,同开发者已经使用的云服务相互兼容,并不互斥。
云开发提供了几大基础能力支持:

云开发的三个主要组成:数据库
存储
云函数
数据库
:云开发提供了一个 JSON 数据库,顾名思义,数据库中的每条记录都是一个 JSON 格式的对象。一个数据库可以有多个集合(相当于关系型数据中的表),集合可看做一个 JSON 数组,数组中的每个对象就是一条记录,记录的格式是 JSON 对象。
关系型数据库和文档型数据库的对比:

demo示例
写一个云开发模式下的数据操作:对数据的增删差改
wxml:
<text>添加</text>
<button bindtap="onAddhandler" type="primary">添加一条记录</button>
<text>查询</text>
<button bindtap="onGethandler" type="primary">查询一条记录</button>
<text>删除</text>
<button bindtap="onDeletehandler" type="primary">删除一条记录</button>
<text>修改</text>
<button bindtap="onUpdatehandler" type="primary">更新一条记录</button>
<text>批量删除</text>
<button bindtap="onDelBathandler" type="primary">批量删除</button>
界面:

添加功能:
onAddhandler: function() {
/**
*添加一条记录
*/
//在开始使用数据库 API 进行增删改查操作之前,需要先获取数据库的引用。以下调用获取默认环境的数据库的引用
const db = wx.cloud.database();
//user是集合的名字
db.collection('user').add({
//data是添加的数据
data: {
"id": 1,
"shop": "张姐烤肉饭脆皮饭",
"picture": "https://image.jpg",
"product": "黑椒脆皮鸡+时蔬+米饭",
"price": "18",
"ifCommented": false
},
}).then(res => {
//添加成功返回的信息
console.log(res)
})
},
添加成功后返回的信息:

添加成功后会自动添加一个随机id作为该记录的唯一标识,还会自动添加openid识别当前操作人(控制台可看)
查询:
onGethandler: function() {
const db = wx.cloud.database();
//doc:当前记录(唯一标识)
db.collection('user').doc('889dfecd5e78259b001c1a5867f4dfdb').get().then(res => {
console.log(res.data)
})
},
查询后返回的信息:

删除:
onDeletehandler: function() {
const db = wx.cloud.database();
db.collection('user').doc('0dee15725e78241a001a5a1c25e3d68d').remove({
success: function(res) {
console.log(res)
}
})
},
修改:
onUpdatehandler: function() {
const db = wx.cloud.database();
db.collection('user').doc('889dfecd5e78259b001c1a5867f4dfdb').update({
//需要更新的数据
data: {
"price": "12345",
},
success: function(res) {
console.log(res)
}
})
},
更新后返回的信息:

批量删除:
批量删除写在云函数里面,然后外部函数来调用。
云函数:
// 云函数入口文件
const cloud = require('wx-server-sdk');
cloud.init(); //初始化
const db = cloud.database();
// 云函数入口函数
exports.main = async(event, context) => {
try {
//删除user集合字段为 price: '18'的记录
return await db.collection('user').where({
price: '18'
}).remove()
} catch (e) {
console.log(e)
}
}
调用函数:
onDelBathandler: function() {
wx.cloud.callFunction({
//云函数的名字
name: 'DeleBat',
success: function(res) {
console.log(res.result)
},
fail: function(e) {
console.log(e)
}
})
},
执行结果:

为了演示我添加了13条有
price: '18'
字段的记录,所以总共移除了13条
网友评论