准备
- 在project.config.json中配置云函数文件夹路径(提前创建好文件夹)

| 1
 | "cloudfunctionRoot": "cloudfunctions/"
 | 
- app.js中对云函数初始化

| 12
 3
 4
 5
 6
 7
 8
 
 | if(!wx.cloud){
 console.log('基础库版本太低');
 }else{
 wx.cloud.init({
 traceUser:true
 })
 }
 
 | 
新建云函数

部署云函数

更新云函数

调用云函数
在某JS页面内:
| 12
 3
 4
 5
 
 | wx.cloud.callFunction({name:"queryCharacter"
 }).then(
 
 )
 
 | 
云函数操作
查
| 12
 3
 4
 5
 6
 7
 
 | const cloud = require('wx-server-sdk')cloud.init()
 let db=cloud.database();
 
 exports.main = async (event, context) => {
 return await db.collection('votes').get();
 }
 
 | 
let db=cloud.database();获取数据库对象实例,db.collection('votes').get()表示获取数据库中votes集合的数据。
增
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | const cloud = require('wx-server-sdk')cloud.init()
 db=cloud.database()
 
 exports.main = async (event, context) => {
 return await db.collection('votes').add({
 data:{
 
 }
 })
 }
 
 | 
删
| 12
 3
 4
 5
 6
 7
 
 | const cloud = require('wx-server-sdk')cloud.init()
 db=cloud.database();
 
 exports.main = async (event, context) => {
 return await db.collection('votes').doc('6360507662518d4704fbfb42750910e8').remove();
 }
 
 | 
db.collection('votes').doc('6360507662518d4704fbfb42750910e8').remove();其中6360507662518d4704fbfb42750910e8
为待删除记录的id。
改
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | const cloud = require('wx-server-sdk')cloud.init()
 db=cloud.database();
 
 exports.main = async (event, context) => {
 return await db.collection('votes').doc('6360507662518f0204fc278b328debe2').update({
 data:{
 favor:10,
 votesNum:100
 }
 })
 }
 
 |