受欢迎的博客标签

微信小程序云开发(28)-小程序云开发实战,客户端后台单一页面的增删改查

Published

回调风格(传入success/fail/complet)

 db.collection('todos').add({
      data:{...},
      success:function(res){...}
   })

  Promise风格(不传入success…)

db.collection('todos').add({
      data:{...}
   }).then(res=>{...})

 

1. miniprogram/pages/admin/Customer/index/index.js

const app = getApp()
const collection_productCategory = 'ProductCategory';
const collection = 'Customer';
const db = wx.cloud.database();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',//修改用来保存_id
    iSshow: true,
    inpVal: '',
    inp2Val: '',
    list: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.getUserMsg()//读取信息
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },


  //获取文本框内容
  getName(e) {
    this.setData({
      inpVal: e.detail.value
    })
  },

  getAge(e) {
    this.setData({
      inp2Val: e.detail.value
    })
  },
  //获取信息
  getUserMsg() {
    var that = this
    db.collection(collection).get({
      success: function (res) {
        console.log(res)
        that.setData({
          list: res.data
        })
      }
    })
  },
  //添加信息
  setUserMsg() {
    var that = this
    if (app.globalData.userInfo == undefined) {
      that.GetUserInfo()
      return
    } else {
      db.collection(collection).add({
        data: {
          created: new Date().getTime(),
          name: that.data.inpVal,
          age: that.data.inp2Val
        },
        success: function (res) {
          console.log(res)
          that.setData({
            inpVal: "",
            inp2Val: ""
          })
          console.log(that.data.inpVal + '--' + that.data.inp2Val)
          that.getUserMsg()
        }
      })
    }
    console.log(app.globalData)
  },
  //删除信息
  delUserMsg(e) {
    var that = this
    var id = e.currentTarget.dataset.id
    db.collection(collection).doc(id).remove({
      success: function (res) {
        console.log(res)
        that.getUserMsg()
      }
    })
  },
  //修改回显
  changeMsg(e) {
    var that = this
    var id = e.currentTarget.dataset.id

    db.collection(collection).doc(id).get({
      success: function (res) {
        that.setData({
          inpVal: res.data.name,
          inp2Val: res.data.age,
          show: false,
          id: res.data._id
        })
      }
    })

  },
  //更新提交
  updetMsg(e) {
    var that = this
    var id = e.currentTarget.dataset.id
    db.collection(collection).doc(id).update({
      data: {
        name: that.data.inpVal,
        age: that.data.inp2Val
      },
      success: function (res) {
        that.getUserMsg()
        that.setData({
          inpVal: '',
          inp2Val: '',
          show: true
        })
      }
    })
  },


})

2.miniprogram/pages/admin/Customer/index/index.wxml

<!--miniprogram/pages/admin/Customer/index/index.wxml-->
<view class="container">
  <view class='box' style='background:#FFFFFF'>
    <label>姓名:</label>
    <input data-value='{{inpVal}}' bindinput='getName' value='{{inpVal}}'></input>
  </view>
  <view class='box' style='background:#FFFFFF;margin-top:10rpx;'>
    <label>年龄:</label>
    <input data-value='{{inpVal}}' bindinput='getAge' value='{{inp2Val}}'></input>
  </view>
  <button wx:if='{{show}}' bindtap='setUserMsg'>提交</button>
  <button wx:if="{{!show}}" data-id="{{id}}" bindtap='updetMsg'>确认修改</button>
</view>
 
 
 
<view class='infoMsg'>
  <view>
    <label>姓名</label>
    <label>年龄</label>
    <label>ID</label>
    <label>操作</label>
  </view>
  <view wx:for="{{list}}">
    <label>{{item.name}}</label>
    <label>{{item.age}}</label>
    <label>{{item.created}}</label>
    <label>
      <text data-id='{{item._id}}' bindtap="delUserMsg">删除</text>
      <text data-id='{{item._id}}' bindtap='changeMsg'>修改</text>
    </label>
  </view>
 
</view>

3.miniprogram/pages/admin/Customer/index/index.wxss

/* miniprogram/pages/admin/Customer/index/index.wxss */
page {
  background: #f6f6f6;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  font-size: 30rpx;
}
.box{
  width: 90%;
  display: flex;
  background: grey
}
button{
  width: 90%;
  height: 40px;
  line-height: 40px;
  margin-top: 20rpx;
  background:#ffffff;
 
}
.infoMsg{
  width: 90%;
  margin: auto;
  margin-top: 20rpx;
  border: 1rpx solid #e2e2e2;
  font-size: 28rpx;
}
.infoMsg view{
  display: flex;
  border-top: 1rpx solid #e2e2e2;
}
.infoMsg view>label{
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.infoMsg view>label:not(:first-child){
  border-left: 1rpx solid #e2e2e2;
}
.infoMsg view>label text{
  margin-right: 10rpx;
  border: 1rpx solid #e2e2e2;
}

 

修改单个field or 原子操作

重点:修改单个field 需用doc(“_id”)确定到单条记录。用where时开发工具不会显示出错信息但也不会修改记录。用真机时会出错。

 //--------------syngoodDB------------------------
  changePassword: function () {
    const db = wx.cloud.database();
    const _ = db.command;
    var passworddbid = this.data.passworddbid;
    db.collection('data1').doc(passworddbid).update({
      data: {
        //默认是更新  style.color  字段为 'blue' 而不是把  style  字段更新为  { color: 'blue' }  对象:
        //如果需要替换更新一条记录,可以在记录上使用  set  方法,替换更新意味着用传入的对象替换指定的记录:
        password: _.set(this.data.password)
      },
      success: res => {
        console.log('[数据库] [更新记录] 成功:', this.data.password);
        wx.showToast({
          title: '[数据库][更新记录] 成功:' + this.data.password,
        })
      },
      fail: err => {
        icon: 'none',
          console.log('[数据库] [更新记录] 失败:', err)
      }
    })
  },

 

小程序云开发_id自定义值

做小程序云开发增加数据时,因为不想用系统生成的值给_id,所以按照网上教程去做,但一直都加不经去,都是失败的例子。为此浪费不少时间,但最后根据api文档,以及看云开发平台解决了。如果你想要自定义_id的值,不想它系统生成,在插入数据的时候_id名改为_id_就可以了。

插入数据:

return await db.collection('users').add({

data:{

_id_: user_open_id,

user_name:user_name,

user_tel:user_tel,

user_department:user_department

}