微信小程序开发云函数更新数据

By gavin
一、创建云函数(包含config.json、index.js、package.json)
--index.js
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
// API 调用都保持和云函数当前所在环境一致
env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
try {
returnawait db.collection('tablename').doc(\_id).update({
// data 传入需要局部更新的数据
data: {
num: event.num
}
})
} catch (e) {
console.error(e)
}
}
--config.json
{
"permissions": {
"openapi": []
}
}
--package.json
{
"name": "update",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"wx-server-sdk": "latest"
}
}
二、上传部署云函数
选中新创建的云函数点击右键,选择上传并部署:云端安装依赖
三、使用云函数
wx.cloud.callFunction({
// 云函数名称
name: 'update',
// 传给云函数的参数
data: {
num: num
},
success: function (res) {
console.log(res)
},
fail: console.error
})
注意:传递的参数需要在云函数中使用event.去获取