微信小程序 学习笔记7 云数据库

新建一个测试页面
test.wxml

<view>
<input type="number" name="code" placeholder="编号" bindinput="bvCode"></input>
<input type="text" name="name" placeholder="名称"  bindinput="bvName"></input>
<input type="number" name="type" placeholder="类型"  bindinput="bvType"></input>
<button type="default" bindtap="addData">写入数据库</button>
</view>

<view>
<button type="default" bindtap="loadData">读数据库</button>
<text name="result">{{result}}</text>
</view>

test.js

Page({
  /**
   * 页面的初始数据
   */
  data: {
    code: 0,
    name: "",
    type: 1,
    result: ""
  },
  // 通过事件绑定code值
  bvCode(e) {
    console.log(e.detail)
    this.setData({
      code: e.detail.value
    })
  },
  // 通过事件绑定name值
  bvName(e) {
    console.log(e.detail)
    this.setData({
      name: e.detail.value
    })
  },
  // 通过事件绑定type值
  bvType(e) {
    console.log(e.detail)
    this.setData({
      type: Number(e.detail.value)
    })
  },
  // 异步新增数据方法
  async addData() {
    // 获取数据库引用
    const db = wx.cloud.database()
    // 新增数据
    await db.collection("test").add({
      data: {
        code: this.data.code,
        name: this.data.name,
        type: this.data.type
      }
    }).then(this.setData({
      result: "写入数据成功."
    }))
  },
  // 异步读取数据方法
  async loadData() {
    this.setData({
      result: "正在读取数据."
    })
    // 获取数据库引用
    const db = wx.cloud.database()
    // 读取记录数数据
    await db.collection('test').count().then(
      res => {
        this.setData({
          result: "云数据共有数据 " + res.total + " 条."
        })
      }
    )
    await db.collection("test").where({
      type: 1
    }).get().then(
      res => {
        console.log(res)
      }
    )
  },
})
原文地址:https://www.cnblogs.com/congxinglong/p/14228193.html