微信小程序云開發(fā)之數(shù)據(jù)庫操作
更新時間:2019年05月18日 10:08:50 作者:十二指環(huán)
這篇文章主要為大家詳細介紹了微信小程序云開發(fā)之數(shù)據(jù)庫操作,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了微信小程序云開發(fā)之數(shù)據(jù)庫操作的具體代碼,供大家參考,具體內容如下
新建集合
1.打開云開發(fā)控制臺,數(shù)據(jù)庫
2.添加集合users
添加代碼
onAdd: function () {
const db = wx.cloud.database()
db.collection('users').add({
data: {
count: 1
},
success: res => {
// 在返回結果中會包含新創(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ù)庫] [新增記錄] 失敗:', 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)
})
console.log('[數(shù)據(jù)庫] [查詢記錄] 成功: ', res)
},
fail: err => {
wx.showToast({
icon: 'none',
title: '查詢記錄失敗'
})
console.error('[數(shù)據(jù)庫] [查詢記錄] 失敗:', 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ù)庫] [更新記錄] 失?。?, 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ù)庫] [刪除記錄] 失敗:', err)
}
})
} else {
wx.showToast({
title: '無記錄可刪,請見創(chuàng)建一個記錄',
})
}
這個官方的demo做的可以,通俗易懂
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
使用CoffeeScrip優(yōu)美方式編寫javascript代碼
CoffeeScript就是JavaScript,他進行的是一對一的編譯,或者說是翻譯,而且編譯成的JavaScript代碼可讀性很強。本文給大家介紹使用CoffeeScript優(yōu)美方式編寫javascript代碼,感興趣的朋友一起看看吧2015-10-10
Intellij中直接運行ts配置方法:run?configuration?for?typescript
run?configuration?for?typescript?插件本質還是依賴于ts-node來運行,只是其可以幫助我們自動配置好ts-node運行參數(shù),簡化使用,這篇文章給大家介紹在Intellij中可以借助插件run?configuration?for?typescript直接運行typescript的方法,感興趣的朋友一起看看吧2023-08-08

