这篇文章写下微信小程序云开发的入门操作,有兴趣的童鞋请往下冲~~
一、创建小程序
-
打开小程序开发工具,新建小程序,选择不使用云服务
-
点击界面中的云开发按钮,开启云服务
云开发控制台如下:
二、操作数据库
- 创建集合
- 添加一条记录
添加成功:
- 获取数据
get()
在页面中写按钮并写上点击事件:
<button bindtap="getdbData">获取数据库数据</button>
在js文件中写点击事件:
// 云能力初始化
wx.cloud.init();
// 获取数据库引用
const db = wx.cloud.database();
Page({
getdbData() {
db.collection('test').get().then(res => {
console.log(res);
})
}
})
返回的信息:
我们刚才在数据库test集合添加了一条数据,但是没有获取到,是因为数据权限没有设置好,默认的数据权限为
仅创建者可读写,当修改为 所有用户可读,仅创建者可读写时,客户端才能获取到数据。
重新设置权限后,客户端重新点击按钮获取数据,可得到数据库中的数据:
- 添加数据
add()
添加一条数据:
adddbData() {
db.collection('test').add({
data: {
username: "小红",
age: 11
}
}).then(res => {
console.log(res);
})
}
返回结果:
- 条件查询
where()
getdbData1() {
db.collection('test').where({age: 12}).get().then(res => {
console.log(res);
})
}
返回结果:
- id查询
doc()
getdbData2() {
db.collection('test').doc('8937eaa96141b59a0b651c3c3dcef7a9').get().then(res => console.log(res))
}
返回结果:
- 更新数据
update()
updatedbData() {
const _this = this;
db.collection('test').where({age: 11}).update({data:{age: 13}}).then(res => {
console.log(res)
_this.getdbData();
})
}
返回结果:
- 删除数据
remove()
removedbData() {
const _this = this;
db.collection('test').where({age: 13}).remove().then(res => {
console.log(res);
_this.getdbData();
})
}
返回结果:
三、云函数
- 配置云函数路径:
- 在根目录下新建文件夹cloudFunctions
- 在project.config.json设置
cloudfunctionRoot字段
"cloudfunctionRoot": "./cloudFunctions",
- 创建并使用云函数
右击cloudFunctions文件夹,选择
新建Node.js云函数,输入云函数名称即可。
修改index.js中的代码:
// 云函数入口文件
const cloud = require('wx-server-sdk')
// 初始化云函数
cloud.init();
exports.main = async (event, context) => {
// 云函数返回值
return {username: "张三"}
}
改动云函数后要在云函数的文件夹右击选取上传并部署,更新云函数。
客户端调用云函数callFunction():
getCloudFn() {
wx.cloud.callFunction({name: "testFn"}).then(res => {
console.log(res);
})
}
返回结果:
3.云函数中使用数据库 注意:
- 要在云函数初始化后再声明数据库对象。
- 云函数返回的数据,在客户端用
res.result获取。 - 云函数不受数据库权限和请求条数的限制。
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 声明数据库对象
const db = cloud.database();
exports.main = async (event, context) => {
return db.collection('test').get().then(res => {
return res;
})
}