小程序云开发笔记总结

715 阅读6分钟

项目创建和配置

  • 创建一个小程序应用,不启动云服务。后面开发中我们再自行开启。
  • 在根目录中创建一个cloudfunctions文件夹
  • 在project.config.json文件中添加上这句代码,添加完成后。可以看到cloudfunctions目录出现绑定了哪个云服务名字
{
	"description": "项目配置文件",
    	"cloudfunctionRoot":"cloudfunctions/",
	"setting": {...},
     ...
}

  • 在扫盲篇已经写过云函数,并且小程序云开发的所有函数都给我上传到云服务器中了。现在这个小程序可以使用之前的云函数。只需要把它们导下来。右击cloudfunctions文件夹同步一下云函数。
  • 导下来的是空文件夹,需要的时候,右击下载该函数

云开发初始化

  • 小程序端初始化,在app文件中添加上配置信息
// app.js
App({
  onLaunch() {
    // 云开发初始化
    wx.cloud.init({
      env: '', 
      //传入字符串形式的环境 ID 可以指定所有服务的默认环境
      
      traceUser: true 
      // 是否在将用户访问记录到用户管理中,在控制台中可见
    })
  },
  globalData: {
    userInfo: null
  }
})

云数据库端

  • 小程序云开发提供的是一个json数据库,可以在云控制台中操作数据库。
    • 云数据库中的表叫集合

数据库

  • 数据库操作都是需要有openID的
插入数据
* 调用api就可以实现云数据库的增加操作了
 // 使用数据库api之前,需要先获取数据库的引用。env字段可以指定使用哪个数据库。如果只有一个可以不填写
      const testDB = wx.cloud.database()
      // 获取集合
      const students = testDB.collection('students')
      // 插入数据可以使用 add() 方法,它有俩个参数:新增数据、回调函数 
      students.add({
        //插入数据
        data:{name:'王路飞',sex:'男',age:'22',love:'变大变长'},
        // 成功回调
        success(res){
          console.log('成功',res);
        },
        // 失败回调
        fail(err){
          console.log('失败',err);
        },
        // 执行结束回调
        complete(comp){
          console.log('结束',comp);
        }
      })
// Promise 风格也是支持的,只要传入对象中没有 success, fail 或 complete。
//那么 add 方法就会返回一个 Promise:
student1s.add({data:{name:'王路飞',sex:'男',age:'22',love:'变大变长'},})
.then(res=>{
  console.log(res);
})

云数据库增删改查的api都同时支持回调风格和 Promise 风格调用

查询数据
// 查询,使用get方法获取数据
  students.doc('b00064a7600e2fa000dab8a650e23c4c').get({
    success(res){
      console.log('搜索',res);
    }
  })
## 也可以使用promise方法
students.doc('28ee4e3e600e394300e681d715274b49').get()
.then((res=>{
  console.log('搜索',res);
}))
  • 查询所有数,服务器一次默认并且最多返回 20 条记录
// 直接去除doc即可搜索所有数据
students.get().then((res=>{
  console.log('搜索',res);
}))
  • where键值对的查询功能并不强大,进行特殊条件的搜索。小程序提供了查询指令来解决。
students.where(
  {sex:'男'}
).get().then((res=>{
  console.log('搜索',res);
}))
查询指令(类似SQL的表达式)
* `api文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/Command.html`
// 引入command
const _ = testDB.command
// 跨字段进行 "或" 操作
students.where(_.or([
  {sex: _.lte(1)},
  {name: "王路飞"}
])).get().then((res=>{
  console.log('搜索',res);
}))
数据更新
  • 数据更新主要有俩个方法
    • updata: 局部更新一个或多个记录
    • set: 替换更新一个记录
// 所有id更换它的数据,如果没有该字段会自动添加字段
const _ = testDB.command
students.doc('b00064a7600e363d00dbdce06d7b32d1').update({
    data: { 
      age: _.inc(55),  // 数据累加,只能用于number
      arr: _.unshift(11), //数组操作
      name: '三橘菜花'  // 更替数据
    }
  }).then(res=>{
    console.log(res);
  })
  
  • 主要是通过command来进行一些特殊操作

    • set: 设置值,可以任意数据类型会自动替换掉类型也会跟着改变。需要传入值
    • remove:删除字段。不需要传入值
    • inc:数据累加,只能用于number类型(加法操作)
    • mul:数据累加,只能用于number类型(乘法操作)
    • push、pop、shift、unshift: 对数组类型的操作、
  • 删除字段,传入id即可删除该数据

const students = testDB.collection('students')
const _ = testDB.command
students.doc('b00064a7600e363d00dbdce06d7b32d1').remove().then(res=>{
        console.log(res);
      })
  },
查询对象数组类型数据.
  • 查询对象数据,搜索某个字段里面对象属性的某一个值
   const students = testDB.collection('students')
   const _ = testDB.command
    students.where({
      //obj:{sex:2} //对象形式搜索
      'obj.sex':1//键值对搜索
    }).get().then(res=>{
      console.log(res);
    })
  • 查询数组类型数据
const students = testDB.collection('students')
const _ = testDB.command
students.where({
  'arr':['bb','cc','aa'] // 匹配数组,所有元素都一致
  'arr':'aa'  // 数组是否有该元素
  'arr.2':'aa' // 数组下标为2的元素值是否一致
  'arr.2':_.eq('aa') //也可以配合查询指令做特殊操作
}).get().then(res=>{
  console.log(res);
})
// 配合查询指令更新数据
const students = testDB.collection('students')
const _ = testDB.command
students.where({
    'arr':'aa'
}).update({
  data: {
    'arr.$': 25
  }
}).then(res=>{
  console.log(res);
})
// 数组所有值累加
students.doc('28ee4e3e600e35a500e5d9d720c2717a').update({
    data: {
      'arr.$[]': _.inc(10)
    }
  }).then(res=>{
    console.log(res);
  })
  • 数据排序
// 倒由大到小排序
students.orderBy('age', 'desc').get().then(res=>{
  console.log(res);
})
  • 过滤数据
// 设为true的字段展示,没有的、false的则不展示
students.field({
    name:true
}).get().then(res=>{
    console.log(res);
})
  • 返回数据条数
students.count().then(res=>{
    console.log(res);
})
  • 监听数据库数据改变
students.doc('28ee4e3e600e35a500e5d9d720c2717a').watch({
  // 记录改变时触发
onChange(res){
    console.log(res.docs[0]);
},
onError(err){
    console.log(err);
}
})
索引和管理端操作
  • 在做数据库操作的时候,控制台会提示 索引建议。这个在云控制台中配置。添加上索引管理他就不会提示了
  • 在管理端也可以对数据库的操作

云函数的使用

第一个云函数
  • 在云函数文件中创建一个云函数,编辑器会自动上传到云端。小程序调用的时候,只会去查找云端上的函数,并不执行本地没上传的云函数。
//云函数 initdb —— index.js
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  return {
    obj: event
  }
}
// 小程序端
onLoad: function (options) {
      //加载 调用云函数,只会在云端中查找该函数
      wx.cloud.callFunction({
        // 云函数名称
        name:'initdb',
        // 云函数传值
        data:{
          name: 'Mr.Lee',
          age:100
        }
      }).then(res=>{
        console.log(res);
        // 这里是可以获取到openid的
      })
  },
  • 编写完成得云函数,也需要上传到云端。小程序调用的代码就是云端的。如果程序不执行,可以看看是不是没有上传到云端
异步返回结果
  • 云函数默认超时时间为3秒,超过了这个时间则报超时错误。可以在云控制台,设置新值。
// 云函数入口函数
exports.main = async (event, context) => {
  // const wxContext = cloud.getWXContext()
  const db = cloud.database()
  return new Promise((resolve, reject)=>{
    setTimeout(()=>{
      resolve(db.collection('students').get()) 
    }, 2000)
  })
}
云存储
  • 上传图片到云数据库
handleClick(){
    wx.chooseImage({
      count: 1,
      sizeType:['original', 'compressed'],
      sourceType:['album', 'camera'],
      success(res){
        //上传至云存储空间
        wx.cloud.uploadFile({
          cloudPath: 'image/这是色图', // 存储路径以及文件取名
          filePath: res.tempFilePaths[0], // 小程序临时文件路径
          success: res => {
            // 返回文件 ID
            console.log(res)
          },
          fail: console.error
        })
      }
    })
  },
  • 文件下载
downloadFile(){
    wx.cloud.downloadFile({
      //云存储
      fileID: 'cloud://w-666-4gzqmb413200111a.772d-w-666-4gzqmb413200111a-1304837727/image/my-image.jpg',
      success: res=>{
        //保存到相册
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success:(res)=>{
            console.log(res);
          }
        })
      }
    })
  }