書庫操作大多需要用戶 openid,需先配置好login雲函數,如已配置好,點擊下一步,獲取用戶的openid並開始我們的指引。
1.打開雲開發控制台,進入到數據庫管理頁。
// 1. 獲取數據庫引用
const db = wx.cloud.database()
// 2. 獲取數據庫集合 counters
// 添加記錄
db.collection('counters').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)
}
})
3.在雲開發->數據庫->counters集合中可以看到新增
// // 查詢當前用戶所有的 counters
db.collection('counters').where({
_openid: this.data.openid
}).get({
success: res => {
this.setData({
queryResult: JSON.stringify(res.data, null, 2)
})
console.log('[數據庫] [查詢記錄] 成功: ', res)
},
fail: err => {
wx.showToast({
icon: 'none',
title: '查詢記錄失敗'
})
console.error('[數據庫] [查詢記錄] 失敗:', err)
}
})
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)
}
})
if (this.data.counterId) {
const db = wx.cloud.database()
db.collection('counters').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: '無記錄可刪,請見創建一個記錄',
})
}