微信小程序云开发入门

474 阅读2分钟

这篇文章写下微信小程序云开发的入门操作,有兴趣的童鞋请往下冲~~

一、创建小程序

  1. 打开小程序开发工具,新建小程序,选择不使用云服务 image.png

  2. 点击界面中的云开发按钮,开启云服务

image.png

云开发控制台如下:

image.png

二、操作数据库

  1. 创建集合 image.png
  2. 添加一条记录 image.png 添加成功: image.png
  3. 获取数据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);
    })
  }
})

返回的信息:

image.png 我们刚才在数据库test集合添加了一条数据,但是没有获取到,是因为数据权限没有设置好,默认的数据权限为 仅创建者可读写,当修改为 所有用户可读,仅创建者可读写时,客户端才能获取到数据。

image.png 重新设置权限后,客户端重新点击按钮获取数据,可得到数据库中的数据:

image.png

  1. 添加数据add()

添加一条数据:

adddbData() {
    db.collection('test').add({
      data: {
        username: "小红",
        age: 11
      }
    }).then(res => {
      console.log(res);
    })
}

返回结果: image.png

  1. 条件查询where()
getdbData1() {
    db.collection('test').where({age: 12}).get().then(res => {
      console.log(res);
    })
}

返回结果:

image.png

  1. id查询doc()
getdbData2() {
    db.collection('test').doc('8937eaa96141b59a0b651c3c3dcef7a9').get().then(res => console.log(res))
}

返回结果:

image.png

  1. 更新数据 update()
updatedbData() {
    const _this = this;
    db.collection('test').where({age: 11}).update({data:{age: 13}}).then(res => {
      console.log(res)
      _this.getdbData();
    })
}

返回结果:

image.png

  1. 删除数据 remove()
removedbData() {
    const _this = this;
    db.collection('test').where({age: 13}).remove().then(res => {
      console.log(res);
      _this.getdbData();
    })
}

返回结果:

image.png

三、云函数

  1. 配置云函数路径:
  • 在根目录下新建文件夹cloudFunctions
  • 在project.config.json设置cloudfunctionRoot字段
  "cloudfunctionRoot": "./cloudFunctions",
  1. 创建并使用云函数 右击cloudFunctions文件夹,选择新建Node.js云函数,输入云函数名称即可。

image.png 修改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);
    })
}

返回结果:

image.png

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;
  })
}

image.png