微信小程序雲開發之雲數據庫入門


微信小程序雲開發之雲數據庫入門

介紹

開發者可以使用雲開發開發微信小程序、小游戲,無需搭建服務器,即可使用雲端能力。
其基礎能力數據庫,是一個JSON數據庫,作用是無需自建數據庫,就可以在微信小程序前端操作數據庫,也能在雲函數中讀寫數據庫。

前置條件

  • 在新建項目是一定要勾選開啟雲服務
  • 在微信開發者工具中點擊雲開發構建集合。

注意事項

數據庫 API 分為小程序端和服務端兩部分,小程序端 API 擁有嚴格的調用權限控制,開發者可在小程序內直接調用 API 進行非敏感數據的操作。對於有更高安全要求的數據,可在雲函數內通過服務端 API 進行操作。雲函數的環境是與客戶端完全隔離的,在雲函數上可以私密且安全的操作數據庫。

簡言之:讀寫數據權限方面,微信小程序最低,雲函數和雲數據庫一樣高。

如果我們需要給予小程序相應權限,也是有辦法的。我們可以在雲開發控制台中設置微信小程序讀取權限來達到自身項目的需求。

實例

該實例包含數據庫開發全過程,涉及鏈接 獲取集合 增刪改查 檢索,新建好名稱為user的集合就能運行,供大家借鑒參考。(增刪改查權限如果雲開發控制台沒有設置,有可能報錯,設置一下即可)

廢話不說,源碼獻上

demo.wxml


<!--index.wxml-->
<view class="container">
  <!-- 用戶 openid -->
  <view class="userinfo">
    <button open-type="getUserInfo" bindgetuserinfo="onGetUserInfo" class="userinfo-avatar" style="background-image: url({{avatarUrl}})" size="default"></button>
    <view class="userinfo-nickname-wrapper">
      <button class="userinfo-nickname" bindtap="onGetOpenid">點擊獲取 openid</button>
    </view>
  </view>
  <!-- 增加數據 -->
  <view class="uploader">
    <view bindtap="addData" class="uploader-text">
      <text>增加數據</text>
    </view>
    <view class="page-body">
      <form catchsubmit="formSubmit" catchreset="formReset" hidden="{{isFormHidden}}">
        <!-- 開關
          <view class="page-section page-section-gap">
            <view class="page-section-title">switch</view>
            <switch name="switch" />
          </view> -->
        <!-- <view class="section">
          <view class="section__title">性別</view>
          <picker bindchange="bindPickerChange" value="{{index}}" range="{{array}}">
            <view class="picker">
              性別: {{array[index]}}
            </view>
          </picker>
        </view> -->
        <!-- 單選
          <view class="page-section page-section-gap">
            <view class="page-section-title">radio</view>
            <radio-group name="radio">
              <label>
                <radio value="radio1" />選項一</label>
              <label>
                <radio value="radio2" />選項二</label>
            </radio-group>
          </view> -->
        <!-- 多選
          <view class="page-section page-section-gap">
            <view class="page-section-title">checkbox</view>
            <checkbox-group name="checkbox">
              <label>
                <checkbox value="checkbox1" />選項一</label>
              <label>
                <checkbox value="checkbox2" />選項二</label>
            </checkbox-group>
          </view> -->
        <!-- 滑動選擇
          <view class="page-section page-section-gap">
            <view class="page-section-title">slider</view>
            <slider value="50" name="slider" show-value></slider>
          </view> -->
        <!-- 輸入框 -->
        <view class="page-section">
          <view class="page-section-title">
            <input class="weui-input" name="userName" placeholder="請輸入用戶名稱" />
          </view>
        </view>
        <!-- 輸入框 -->
        <view class="page-section">
          <view class="page-section-title">
            <input class="weui-input" name="itCard" placeholder="請輸入昵稱" />
          </view>
        </view>
        <!-- 輸入框 -->
        <view class="page-section">
          <view class="page-section-title">
            <input class="weui-input" name="phone" placeholder="請輸入電話" />
          </view>
        </view>
        <!-- 輸入框 -->
        <view class="page-section">
          <view class="page-section-title">
            <input class="weui-input" name="email" placeholder="請輸入郵箱" />
          </view>
        </view>
        <!-- 提交 -->
        <view class="btn-area">
          <button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">提交</button>
          <button style="margin: 30rpx 0" type="primary" formType="submit">Submit</button>
          <button style="margin: 30rpx 0" formType="reset">Reset</button>
        </view>
      </form>
    </view>
  </view>
  <!-- 查看數據 -->
  <view class="uploader">
    <view bindtap="seeData" class="uploader-text">
      <text>查看數據</text>
    </view>
    <view class="uploader-text" wx:for="{{user}}" wx:key="key">
      <text>{{item.userName}}</text>
    </view>
  </view>
  <!-- 修改數據 -->
  <view class="uploader">
    <view bindtap="updata" class="uploader-text">
      <text>修改數據</text>
    </view>
    <view class="page-body">
      <form catchsubmit="updatasubmit" catchreset="updatareset" hidden="{{isupdataform}}">
        <view class="btn-area">
          <input name="userName" placeholder="重新輸入姓名"></input>
        </view>
        <view class="btn-area">
          <button style="margin:30rpx 0" type="primary" formType="submit">更新</button>
          <button style="margin:30rpx 0" type="warn" formType="reset">重置</button>
        </view>
      </form>
    </view>
  </view>
  <!-- 刪除數據 -->
  <view class="uploader">
    <view bindtap="deleteData" class="uploader-text">
      <text>刪除最近一條數據</text>
    </view>
    <view class="uploader-text" wx:for="{{users}}" wx:key="key">
      <text>{{item.userName}}</text>
    </view>
  </view>
  
</view>

demo.js


//index.js
const app = getApp()

//獲取數據庫環境引用
const db = wx.cloud.database({
  env: "輸入自己的數據庫環境,也可不輸入,不輸入默認查找當前環境"
})

//鏈接數據庫中的集合
const pave = db.collection("PavmentRecord")
const user = db.collection("user")

// util.js
//格式化日期,輸出格式為y-m-d h m s
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute].map(formatNumber).join(':')   //返回年月日,時分秒
}

//轉換int類型為string
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


Page({
  data: {
    avatarUrl: '../../images/user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    requestResult: '',
    isFormHidden: true,
    isupdataform: true,
    users: {},
    array: ['男', '女'],
    cloud: ''
  },
  onShareAppMessage() {
    return {
      title: 'picker-view',
      path: 'page/component/pages/picker-view/picker-view'
    }
  },
  onLoad: function () {
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }
    var that = this
    // 獲取用戶信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已經授權,可以直接調用 getUserInfo 獲取頭像昵稱,不會彈框
          wx.getUserInfo({
            success: res => {
              that.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
  },
  bindPickerChange: function (e) {
    console.log('picker發送選擇改變,攜帶值為', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  onGetUserInfo: function (e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },
  onGetOpenid: function () {
    // 調用雲函數
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[雲函數] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '../userConsole/userConsole',
        })
      },
      fail: err => {
        console.error('[雲函數] [login] 調用失敗', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },
  //增加數據
  addData: function () {
    this.setData({
      isFormHidden: false
    })
  },
  getPhoneNumber: function (e) {
    console.log(e)
  },
  //提交表單
  formSubmit(e) {
    const ur = e.detail.value;
    console.log("提交表單信息如下:")
    console.lot(ur)
    var date = formatTime(new Date());
    console.log(date)
    pave.add({
      data: {
        userName: 'test',
        userPhone: '15239942334',
        diseaseName: "test",
        symCom: "test",
        recordTime: date,
        payMoney: 100.0
      },
    }).then(res => {
      console.log(res)
    }).catch(function (e) {
      console.log(e)
    })
  },
  //重置表單
  formReset(e) {
    console.log('form發生了reset事件,攜帶數據為:', e.detail.value)
    this.setData({
      chosen: ''
    })
  },
  //查看數據
  seeData(e) {
    user.get().then(
      res => {
        console.log(res.data)
        this.setData({
          user: res.data
        })
      }
    )
  },
  //修改數據
  updata(e) {
    this.setData({
      isupdataform: false
    })
  },
  updatasubmit(e) {
  //查找user集合中id為以下數據的值,可以在e中獲取,這里我簡單寫了一個。
    user.where({
      "_id": 'dc277a235f081fc20009534043d370cc'
    }).set({
      data: {
        "userName": e.data.userName
      },
      success: function (res) {
        console.log("更新成功:" + res)
      }
    })
  },
  updatareset(e) {
    this.setData({
      chosen: ''
    })
  },
  deleteData(e) {
    var that
    wx.cloud.callFunction({
      name: 'deleteData',
      data: {
        object: 'user',
        id: 'a7d38b365f0852c2000c0a3b0b7aae7a'
      }
    }).then(res => {
      console.log(res)
      that = res.data
    })

  }
})


demo.wxss


/**index.wxss**/
page {
  background: #f6f6f6;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.userinfo, .uploader, .tunnel {
  margin-top: 40rpx;
  height: 140rpx;
  width: 100%;
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-left: none;
  border-right: none;
  display: flex;
  flex-direction: row;
  align-items: center;
  transition: all 300ms ease;
}
.userinfo {
  padding-left: 120rpx;
}
.userinfo-avatar {
  width: 100rpx;
  height: 100rpx;
  margin: 20rpx;
  border-radius: 50%;
  background-size: cover;
  background-color: white;
}
.userinfo-avatar[size] {
  width: 100rpx;
}
.userinfo-avatar:after {
  border: none;
}
.userinfo-nickname {
  font-size: 32rpx;
  color: #007aff;
  background-color: white;
  background-size: cover;
  text-align: left;
  padding-left: 0;
  margin-left: 10px;
}
.userinfo-nickname::after {
  border: none;
}
.userinfo-nickname-wrapper {
  flex: 1;
}
.uploader, .tunnel {
  height: auto;
  padding: 0 0 0 40rpx;
  flex-direction: column;
  align-items: flex-start;
  box-sizing: border-box;
}
.uploader-text, .tunnel-text {
  width: 100%;
  line-height: 52px;
  font-size: 34rpx;
  color: #007aff;
}
.uploader-container {
  width: 100%;
  height: 400rpx;
  padding: 20rpx 20rpx 20rpx 0;
  display: flex;
  align-content: center;
  justify-content: center;
  box-sizing: border-box;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.uploader-image {
  width: 100%;
  height: 360rpx;
}
.tunnel {
  padding: 0 0 0 40rpx;
}
.tunnel-text {
  position: relative;
  color: #222;
  display: flex;
  flex-direction: row;
  align-content: center;
  justify-content: space-between;
  box-sizing: border-box;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.tunnel-text:first-child {
  border-top: none;
}
.tunnel-switch {
  position: absolute;
  right: 20rpx;
  top: -2rpx;
}
.disable {
  color: #888;
}
.service {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  background: linear-gradient(#007aff, #0063ce);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
  display: flex;
  align-content: center;
  justify-content: center;
  transition: all 300ms ease;
}
.service-button {
  position: absolute;
  top: 40rpx;
}
.service:active {
  box-shadow: none;
}
.request-text {
  padding: 20rpx 0;
  font-size: 24rpx;
  line-height: 36rpx;
  word-break: break-all;
}


demo.json


{
  "usingComponents": {},
  "navigationBarTitleText":"數據操作"
}


更多微信小程序相關查看我的程序員提升專欄,有需要請評論區留言。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM