1. 创建集合

首先开通微信小程序的云开发环境,然后打开云开发控制台,添加集合。因为我做的是记账的微信小程序,所以创建了一个userbills 集合。

2. 记录数据



  1. /* mydata ={
  2. money: 88,
  3. date: '2018-12-28',
  4. first_level: '账单的父类别',
  5. child_level: '账单的子类别',
  6. info: '账单的备注信息'
  7. } */

  8. const db = wx.cloud.database();
  9. const collections = db.collection('userbills');
  10. collections.add({
  11. data: {
  12. data: mydata,
  13. time: util.formatTime(new Date())
  14. },
  15. success(result) {
  16. app.globalData.myid = result._id,
  17. app.globalData.mydata = mydata,
  18. console.log('add')
  19. that.postbillsuccess()
  20. }
  21. })

添加之后数据库里的结构是这样的:(_id, _openid字段是默认插入的,openid就是用户的认证信息)

小程序如何调用MySQL里数据 小程序接入数据库_字段

3. 查询

查询推荐在云函数里查询,因为前端写的查询,一次最多只能返回20条数据(当然结合分页来使用还是挺好的)。而在云函数查询数据库,一次最多可以返回100条数据,数据量大的时候可以节省数据库读的次数。


1. const db = cloud.database()
2. const MAX_LIMIT = 100
3. const collections = db.collection('usersbill')
4. const _ = db.command
5. const wxContext = cloud.getWXContext()
6. var firstdate = event.firstdate; // 前端调用云函数时传入的时间参数,用来取对应区间里的账单数据
7. var lastdate = event.lastdate;
8. const countResult = await collections.where({
9. _openid: wxContext.OPENID, // 这里需要注意,写数据的时候,会自动为我们添加用户的openid,可是读取的时候,需要自己把这个限制条件加上去。
10. data: {
11. date: _.and(_.gte(firstdate), _.lte(lastdate))
12. }
13. }).count() // 获取该区间段所有的账单总数
14. const total = countResult.total
15. // 计算需分几次取
16. const batchTimes = Math.ceil(total / 100)
17. // 承载所有读操作的 promise 的数组
18. const tasks = []
19. for (let i = 0; i < batchTimes; i++) {
20. const promise = collections.where({
21. _openid: wxContext.OPENID,
22. data: {
23. date: _.and(_.gte(firstdate), _.lte(lastdate))
24. }
25. }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
26. tasks.push(promise)
27. }
28. // 等待所有
29. return (await Promise.all(tasks)).reduce((acc, cur) => ({
30. data: acc.data.concat(cur.data),
31. errMsg: acc.errMsg,
32. }))

涉及到数据库和查询,当然要创建索引来增加查询的速度,这个查询一共是根据两个字段的,'_openid' 和 'data.date' 两个字段,所以,我们在索引处添加这两个字段。

小程序如何调用MySQL里数据 小程序接入数据库_小程序如何调用MySQL里数据_02

 4. 更新字段

更新字段,


1. // myid 是所要更新的数据的 _id
2. 
3. collections.doc(myid).update({
4. data:{
5. data: mydata // 更新的字段以及数值
6. },
7. success:res=>{
8. console.log(res)
9. },fail: err=>{
10. console.log(err)
11. }
12. })

5. 删除数据

删除数据


1. collections.doc(id).remove({
2. success: function (res) {
3. console.log(res)
4. wx.showToast({
5. title: '删除成功',
6. icon: 'success',
7. duration: 2000
8. })
9. }
10. })