1.云函数中的数据添加需要在云函数中做以下三步:
(1)sdk的引用与初始化
(2)数据库引用对象的创建
(3)数据库的链接
具体代码如下:
// 云函数入口文件,此句为对sdk的引入
const cloud = require('wx-server-sdk')
//初始化sdk的cloud
cloud.init()
//创建数据库的引用对象db
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
//对数据库expressDate进行连接,并使用add()方法向数据库中添加数据
return await db.collection('expressDate').add({
data:{
code:"1678",
company:"京东",
describe:"衣物",
phone:"3567"
}
})
}
2.在wxml文件中创建点击事件
<!-- 使用bindtap属性绑定点击事件,其中bindtap后的值为你将要在js文件中创建的函数名 -->
<button bindtap="addFuction">添加数据</button>
3.在页面的js文件中对点击事件进行处理
// res参数是用来接收云函数中的返回值的,没有它你无法接收到云函数执行后的结果
addFuction(res){
// 调用云函数的固定语句
wx.cloud.callFunction({
// 使用name标明所要链接的云函数
name:"addDate",
// 使用data向云函数中传递数据
data:{a:1}
}).then(console.log(res))//使用then打印云函数返回的结果
}