微信小程序雲開發之數據庫操作


本文實例為大家分享了微信小程序雲開發之數據庫操作的具體代碼,供大家參考,具體內容如下

新建集合

1.打開雲開發控制台,數據庫

2.添加集合users

添加代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
onAdd: function () {
const db = wx.cloud.database()
db.collection( 'users' ).add({
data: {
count: 1
},
success: res => {
// 在返回結果中會包含新創建的記錄的 _id
this .setData({
counterId: res._id,
count: 1
})
wx.showToast({
title: '新增記錄成功' ,
})
console.log( '[數據庫] [新增記錄] 成功,記錄 _id: ' , res._id)
},
fail: err => {
wx.showToast({
icon: 'none' ,
title: '新增記錄失敗'
})
console.error( '[數據庫] [新增記錄] 失敗:' , err)
}
})
},

查詢記錄

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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( '[數據庫] [查詢記錄] 成功: ' , res)
},
fail: err => {
wx.showToast({
icon: 'none' ,
title: '查詢記錄失敗'
})
console.error( '[數據庫] [查詢記錄] 失敗:' , err)
}
})
},

更新記錄

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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( '[數據庫] [更新記錄] 失敗:' , 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( '[數據庫] [更新記錄] 失敗:' , err)
}
})
},

刪除記錄

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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( '[數據庫] [刪除記錄] 失敗:' , err)
}
})
} else {
wx.showToast({
title: '無記錄可刪,請見創建一個記錄' ,
})
}

這個官方的demo做的可以,通俗易懂

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。


免責聲明!

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



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