一、前提條件:
登錄開發(fā)者工具軟件 , 配置數(shù)據(jù)庫數(shù)據(jù)集,操作如下:
- 打開云開發(fā)控制臺
- 添加集合User

文章插圖

文章插圖
//增加新紀錄到云數(shù)據(jù)庫
onAdd: function () {
const db = wx.cloud.database()
db.collection(‘users’).add({
data: {
count: 1
},
success: res => {
// 在返回結(jié)果中會包含新創(chuàng)建的記錄的 _id
this.setData({
counterId: res._id,
count: 1
})
wx.showToast({
title: ‘新增記錄成功’,
})
console.log(‘[數(shù)據(jù)庫] [新增記錄] 成功,記錄 _id: ‘, res._id)
},
fail: err => {
wx.showToast({
icon: ‘none’,
title: ‘新增記錄失敗’
})
console.error(‘[數(shù)據(jù)庫] [新增記錄] 失?。?#8217;, err)
}
})
},
三、查詢、更新、刪除和新增
①查詢
onQuery: function() {
const db = wx.cloud.database()
// 查詢當前用戶所有的 counters
db.collection(‘users’).where({
_openid: this.data.openid
}).get({
success: res => {
console.log(res);
this.setData({
queryResult: JSON.stringify(res.data, null, 2)
})
【小程序后端數(shù)據(jù)庫搭建 微信小程序數(shù)據(jù)庫怎么建立】console.log(‘[數(shù)據(jù)庫] [查詢記錄] 成功: ‘, res)
},
fail: err => {
wx.showToast({
icon: ‘none’,
title: ‘查詢記錄失敗’
})
console.error(‘[數(shù)據(jù)庫] [查詢記錄] 失?。?#8217;, err)
}
})
},
②更新
onCounterInc: function() {
const db = wx.cloud.database()
const newCount = this.data.count + 1
db.collection(‘users’).doc(this.data.counterId).update({
data: {
count: newCount
},
success: res => {
console.log(res);
this.setData({
count: newCount
})
},
fail: err => {
icon: ‘none’,
console.error(‘[數(shù)據(jù)庫] [更新記錄] 失敗:’, err)
}
})
},
onCounterDec: function() {
const db = wx.cloud.database()
const newCount = this.data.count – 1
db.collection(‘users’).doc(this.data.counterId).update({
data: {
count: newCount
},
success: res => {
this.setData({
count: newCount
})
},
fail: err => {
icon: ‘none’,
console.error(‘[數(shù)據(jù)庫] [更新記錄] 失?。?#8217;, err)
}
})
},
③刪除
if (this.data.counterId) {
const db = wx.cloud.database()
db.collection(‘users’).doc(this.data.counterId).remove({
success: res => {
wx.showToast({
title: ‘刪除成功’,
})
this.setData({
counterId: ”,
count: null,
})
},
fail: err => {
wx.showToast({
icon: ‘none’,
title: ‘刪除失敗’,
})
console.error(‘[數(shù)據(jù)庫] [刪除記錄] 失?。?#8217;, err)
}
})
} else {
wx.showToast({
title: ‘無記錄可刪,請見創(chuàng)建一個記錄’,
})
}
以上關(guān)于本文的內(nèi)容,僅作參考!溫馨提示:如遇健康、疾病相關(guān)的問題,請您及時就醫(yī)或請專業(yè)人士給予相關(guān)指導!
「愛刨根生活網(wǎng)」www.malaban59.cn小編還為您精選了以下內(nèi)容,希望對您有所幫助:- 紅燒排骨用大排還是小排 紅燒排骨怎樣做好吃又簡單
- 小兒氨酚黃那敏顆粒是什么作用 小兒氨酚黃那敏顆粒
- 辣椒糊糊制作簡單 辣椒糊糊詳細做法
- 私處美容小常識:私處瘙癢能用熱水洗嗎
- 如何有效減小Win10系統(tǒng)盤的使用空間
- 提升文件安全性的WinRAR小技巧
- 為什么小電影里總有吞jing行為
- 如何在PS 2018中調(diào)整曲線面板網(wǎng)格大小
- 如何在Word文檔中輕松設(shè)置信紙大小
- 小腿酸脹痛什么原因 小腿酸脹痛什么原因引起的
