微信小程序云开发数据库操作更新记录

官方文档解读:

代码语言:javascript
复制
<!-- 更新记录 -->
  <view class="guide" wx:if="{{step === 5}}">
    <text class="headline">更新记录</text>
    <text class="p">1. 打开 pages/databaseGuide/databaseGuide.js 文件,定位到 onCounterInc 和 onCounterDec 方法</text>
    <text class="p">2. 把注释掉的代码解除注释</text>
    <image class="code-image" src="../../images/code-db-inc-dec.png" mode="aspectFit"></image>
    <text class="p">3. 点击下方按钮更新计数器</text>
    <div class="counter">
      <button class="minus" size="mini" type="default" bindtap="onCounterDec">-</button>
      <text class="p">{{count}}</text>
      <button class="plus" size="mini" type="default" bindtap="onCounterInc">+</button>
    </div>
&lt;div class=&#34;nav&#34;&gt;
  &lt;button class=&#34;prev&#34; size=&#34;mini&#34; type=&#34;default&#34; bindtap=&#34;prevStep&#34;&gt;上一步&lt;/button&gt;
  &lt;button class=&#34;next&#34; size=&#34;mini&#34; type=&#34;default&#34; bindtap=&#34;nextStep&#34;&gt;下一步&lt;/button&gt;
&lt;/div&gt;

</view>

wxml:

代码语言:javascript
复制
<div class="counter">
<button class="minus" size="mini" type="default" bindtap="onCounterDec">-</button>
<text class="p">{{count}}</text>
<button class="plus" size="mini" type="default" bindtap="onCounterInc">+</button>
</div>

js:

代码语言:javascript
复制
// pages/databaseGuide/databaseGuide.js
const app = getApp()
Page({

data: {
step: 1,
counterId: '',
openid: '',
count: null,
queryResult: '',
},

onLoad: function (options) {
if (app.globalData.openid) {
this.setData({
openid: app.globalData.openid
})
}
},

onCounterInc: function() {
const db = wx.cloud.database()
const newCount = this.data.count + 1
db.collection('counters').doc(this.data.counterId).update({
data: {
count: newCount
},
success: res => {
this.setData({
count: newCount
})
},
fail: err => {
icon: 'none',
console.error('[数据库] [更新记录] 失败:', err)
}
})
},

onCounterDec: function() {
const db = wx.cloud.database()
const newCount = this.data.count - 1
db.collection('counters').doc(this.data.counterId).update({
data: {
count: newCount
},
success: res => {
this.setData({
count: newCount
})
},
fail: err => {
icon: 'none',
console.error('[数据库] [更新记录] 失败:', err)
}
})
},
})

效果如下:

http://recordit.co/NUyzs7XneE