微信小程序云开发
一、开发准备
新建项目选择一个空目录,填入AppID
1.project.confg.json中增加了字段cloudfunctionRoot用于指定存放云函数的目录,在项目根目录下创建cloud文件夹
"description": "项目配置文件",
"cloudfunctionRoot": "cloud",
2.在app.js中进行初始化云开发
App({
onLaunch() {
wx.cloud.init({
env: 'cloud1-4gydzrjnd3e45911', //环境ID来自于,云开发->设置->环境ID
traceUser:true
})
}
})
3.连接数据库,在该页面的最上面引入云数据库。
const db = wx.cloud.database()
二、云数据库
初始化
在开始使用数据库 API 进行增删改查操作之前,需要先获取数据库的引用。以下调用获取默认环境的数据库的引用:
const db = wx.cloud.database()
要操作一个集合,需先获取它的引用。在获取了数据库的引用后,就可以通过数据库引用上的 collection
方法获取一个集合的引用了,比如获取待办事项清单集合:
const todos = db.collection('todos')
插入数据
可以通过在集合对象上调用 add
方法往集合中插入一条记录。
data: {
val:""
},
pushIpt:function(e){
var val = e.detail.value;
this.setData({
val:val
})
},
btnAdd: function () {
db.collection("clouddemo").add({
data: {
name: this.data.val,
contact: "10010",
},
success: (res) => {
console.log(res);
},
});
},
删除数据
对记录使用 remove
方法可以删除该条记录,比如:
btnDel: function () {
// doc 只能根据id来删除
db.collection("clouddemo")
.doc("cd045e756121062906fee3a50e67faf1")
.remove({
success: (res) => {
console.log(res);
},
});
// where 可以根据条件来删除
db.collection("clouddemo")
.where({ name: "王五" })
.remove({
success: (res) => {
console.log(res);
},
});
},
更新数据
API | 说明 |
---|---|
update | 局部更新一个或多个记录 |
set | 替换更新一个记录 |
局部更新
使用 update
方法可以局部更新一个记录或一个集合中的记录,局部更新意味着只有指定的字段会得到更新,其他字段不受影响。
btnUpdata() {
db.collection("clouddemo")
.doc("cd045e7561210f9607003923228201bb")
.update({
data: {
name: "罗翔",
contact:"110",
qq:666,
posttime:new Date()
},
success: res => {
console.log(res);
},
});
},
替换更新
如果需要替换更新一条记录,可以在记录上使用 set
方法,替换更新意味着用传入的对象替换指定的记录:
btnUpdata() { db.collection("clouddemo") .doc("cd045e7561210fc80700412f7b901154") .set({ data: { name: "塔姆", }, success: (res) => { console.log(res); }, }); },
查询数据
在记录和集合上都有提供 get
方法用于获取单个记录或集合中多个记录的数据。
btnGet() { db.collection("clouddemo") .where({ name: "罗翔", }) .get() .then((res) => { console.log(res); this.setData({ getArr: res.data, }); }); },
查询条件
limit
指定查询结果集数量上限
skip
指定查询返回结果时从指定序列后的结果开始返回,常用于分页
orderBy
方法接受一个必填字符串参数 fieldName 用于定义需要排序的字段,一个字符串参数 order 定义排序顺序。
field
方法接受一个必填对象用于指定需返回的字段,对象的各个 key 表示要返回或不要返回的字段
触底查询新内容
getLimit(sp=0) { this.setData({ page:sp }) db.collection("clouddemo") .limit(4) .skip(sp*4) .get() .then((res) => { console.log(res.data); }); }, onReachBottom: function () { let page = this.data.page; page++; this.getLimit(page); },
查询条件限制
//查询条件限制 getLimit(sp = 0) { this.setData({ page: sp, }); // db.collection("clouddemo") // .limit(4) // .skip(sp * 4) // .get() // .then((res) => { // console.log(res.data); // }); db.collection("clouddemo") .orderBy("age", "desc") .orderBy("_id", "desc") .field({ name: true, age:true }) .get() .then((res) => { console.log(res.data); }); },
count
统计匹配查询条件的记录的条数
get
获取集合数据,或获取根据查询条件筛选后的集合数据
// 获取个数的方法 getListArr() { // db.collection("clouddemo") // .get() // .then((res) => { // console.log(res.data.length); // }); db.collection("clouddemo") .count() .then((res) => { console.log(res.total); }); },
watch
监听集合中符合查询条件的数据的更新事件。使用 watch
时,支持 where
, orderBy
, limit
,不支持 field
// 在页面中渲染数据 getArr() { db.collection("clouddemo") .get() .then((res) => { this.setData({ dataArr: res.data, }); }); }, this.getArr(); db.collection("clouddemo") .watch({ onChange: (res) => { this.setData({ dataArr: res.docs, }); }, onError: (err) => { console.log(err); }, });
Command
数据库操作符,通过 db.command
获取
查询·比较操作符
// 链接数据库const db = wx.cloud.database();const _ = db.command;getQuery() { db.collection("clouddemo") .where({ // name:_.eq("小红") 查询姓名等于小红的 // name:_.neq("小红") 查询姓名不等于小红的 // age: _.lt(18), 查询年龄小于18的 // age: _.gt(18), 查询年龄大于18的 // age: _.in([18,21]) 查询在这个数组里的 age: _.nin([18,21]) }) .get() .then((res) => { // console.log(res); this.setData({ dataArr: res.data, }); }); },
查询·逻辑操作符
getQuery() { db.collection("clouddemo") .where({ // age:_.gt(16).and(_.lt(24)) 查询操作符,用于表示逻辑 "与" 的关系,表示需同时满足多个查询筛选条件 // age: _.eq(18).or(_.eq(21)), 查询操作符,用于表示逻辑 "或" 的关系,表示需同时满足多个查询筛选条件。 // age: _.eq(18).not(_.eq(21)), 查询操作符,用于表示逻辑 "非" 的关系,表示需不满足指定的条件。 // age: _.eq(18).nor(_.eq(21)), 查询操作符,用于表示逻辑 "都不" 的关系,表示需不满足指定的所有条件。 }) .get() .then((res) => { // console.log(res); this.setData({ dataArr: res.data, }); }); },
and还可以用在根查询条件
getQuery2() { db.collection("clouddemo") .where( _.and( { name: "小红", }, { age: _.gt(20), } ) ) .get() .then((res) => { // console.log(res); this.setData({ dataArr: res.data, }); }); },
查询·数组操作符
getQuery3() { db.collection("clouddemo") .where({ // like: _.all(["跑步"]), 数组查询操作符。用于数组字段的查询筛选条件,要求数组字段中包含给定数组的所有元素。 // like:_.size(2) 用于数组字段的查询筛选条件,要求数组中包含至少一个满足 elemMatch 给定的所有条件的元素 }) .get() .then((res) => { // console.log(res); this.setData({ dataArr: res.data, }); }); },
更新·字段操作符
getQuery4() { db.collection("clouddemo") .doc("cd045e7561210f9607003923228201bb") .update({ data: { // qq: _.remove(), 更新操作符,用于表示删除某个字段 // age: _.inc(10), 更新操作符,原子操作,用于指示字段自增 }, }) .then((res) => { // console.log(res); this.setData({ dataArr: res.data, }); }); },
更新·数组操作符
getQuery5() { db.collection("clouddemo") .doc("cd045e7561210f9607003923228201bb") .update({ data: { // like: _.unshift(["aaa", "bbb"]), 对一个值为数组的字段,往数组头部添加一个或多个值 // like: _.shift(), 对一个值为数组的字段,将数组头部元素删除。 // like: _.push(["打篮球","社会摇"]), 对一个值为数组的字段,往数组添加一个或多个值 // like: _.pop(), 对一个值为数组的字段,将数组尾部元素删除 // like: _.push({ // each:["旅行"], // position:1, 从第二个位置开始插入 // sort:-1 排序 // }), // like: _.pull("l") 给定一个值或一个查询条件,将数组中所有匹配给定值或查询条件的元素都移除掉。 }, }) .then((res) => { // console.log(res); this.setData({ dataArr: res.data, }); }); },
三、云函数
1、基本使用
1、创建云函数
2、写云函数
// 云函数入口文件const cloud = require("wx-server-sdk");cloud.init();// 云函数入口函数exports.main = async (event, context) => { return event.a + event.b;};
3、上传并且部署
4、绑定云函数
// 获取数据 getData(){ wx.cloud.callFunction({ //云函数使用 name:"demo", //绑定函数的名字 data:{ //发送过去的数据 a:123, b:456 }, success:res=>{ //成功回调 console.log(res); } }) },
2、云函数处理数据库
云函数端
// 云函数入口文件const cloud = require("wx-server-sdk");cloud.init();// 连接数据库const db = cloud.database();// 云函数入口函数exports.main = async (event, context) => { return await db.collection("clouddemo").count()};
小程序端
getData() { wx.cloud.callFunction({ //云函数使用 name: "demo", //绑定函数的名字 success: (res) => { console.log(res.result.total); this.setData({ num:res.result.total //保存获取的数据 }) }, fail: console.error }); },
async和await
async getThen() { console.log("11"); const getDb = await db.collection("clouddemo").get(); console.log(getDb); },
云函数添加数据
小程序端
getData() { wx.cloud.callFunction({ name: "demo", //绑定函数的名字 data: { name: this.data.iptVal }, }).then(res => { console.log(res); }); }, // 获取表单数据 bindIpt(e) { // console.log(e.detail.value); this.setData({ iptVal: e.detail.value, }); },
云函数端
// 云函数入口文件const cloud = require("wx-server-sdk");cloud.init();// 连接数据库const db = cloud.database();// 云函数入口函数exports.main = async (event, context) => { const wxContext = cloud.getWXContext() var name = event.name; return await db.collection("clouddemo").add({ data: { _openid: wxContext.OPENID, name: name, posttime: db.serverDate() }, });};
四、云存储
1、存储图片到云存储中
// 获取云函数数据 clickBtn() { wx.cloud .callFunction({ name: "demo2", }) .then((res) => { console.log(res.result.data); this.setData({ dataArr: res.result.data, }); }); }, // 上传图片 onUpload() { wx.chooseImage({ sizeType: ["original", "compressed"], sourceType: ["album", "camera"], }).then((res) => { console.log(res.tempFilePaths); this.setData({ fileTem: res.tempFilePaths, }); }); }, // 上传云存储 cloudFile() { var fileTem = this.data.fileTem; if (fileTem.length > 0) { fileTem.forEach((item, idx) => { wx.cloud .uploadFile({ cloudPath: new Date().getTime() + "_" + idx + ".jpg", filePath: item, }) .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }); }); } }, // 关闭图像按钮 onClost(e) { var idx = e.currentTarget.dataset.idx; var fileTem = this.data.fileTem; fileTem.splice(idx, 1); this.setData({ fileTem: fileTem, }); },
2、存储视频到云存储中
// 选择视频 getVideo() { wx.chooseVideo({ sourceType: ["album", "camera"], maxDuration: 60, camera: "back", success: (res) => { // console.log(res.tempFilePath); wx.showLoading({ title: "加载中", }); this.fileCloud(res.tempFilePath, new Date().getTime()); }, }); }, // 上传视频 fileCloud(tem, file) { wx.cloud.uploadFile({ cloudPath: file + ".mp4", filePath: tem, success: (res) => { // console.log(res.fileID); if (res.fileID) { wx.hideLoading(); } this.setData({ videoSrc: res.fileID, }); }, fail: console.error, }); },
五、案例
const db = wx.cloud.database();Page({ /** * 页面的初始数据 */ data: { iptVal: "", upFileAll: [], cloudFile: [], }, // 获取输入框内容 bindIpt(e) { console.log(e.detail.value); this.setData({ iptVal: e.detail.value, }); }, // 选择文件 upFile() { wx.chooseMessageFile({ success: (res) => { console.log(res.tempFiles); this.setData({ upFileAll: res.tempFiles, }); }, }); }, // 点击提交 onSubmit() { wx.showLoading({ title: "发布中,请稍后", }); var upFileAll = this.data.upFileAll; upFileAll.forEach((item, idx) => { var tem = item.path; var filename = item.time + "_" + idx + "_" + item.name; this.cloudFile(tem, filename, idx); }); }, // 发送到云存储 cloudFile(tem, filename, idx) { wx.cloud .uploadFile({ cloudPath: filename, filePath: tem, }) .then((res) => { this.data.upFileAll[idx].path = res.fileID; this.data.cloudFile.push(res); if (this.data.upFileAll.length == this.data.cloudFile.length) { this.pushDb(); } // console.log(this.data.cloudFile); }); }, // 发送到数据库 pushDb() { db.collection("demo") .add({ data: { title: this.data.iptVal, upFileAll: this.data.upFileAll, posttime: new Date(), }, }) .then((res) => { wx.hideLoading(); wx.showToast({ title: "发表成功", icon: "success", success: (res) => { this.getListFile(); }, }); }); }, // 渲染初始化列表 getListFile() { db.collection("demo") .get() .then((res) => { // console.log(res); this.setData({ fileList: res.data, }); }); }, // 下载文件 downFile(e) { var fileid = e.currentTarget.dataset.fileid; console.log(fileid); wx.cloud .downloadFile({ fileID: fileid, }) .then((res) => { // console.log(res.tempFilePath); wx.openDocument({ filePath: res.tempFilePath, success: function (res) { console.log("打开文档成功"); }, }); }); }, onLoad: function (options) { this.getListFile(); },});