先初始化數據庫數據庫
const db = wx.cloud.database()
1. 插入操做函數
// collection('user') 獲取到數據庫中名爲 user 的集合 // add 插入操做 db.collection('user').add({ // 要插入的數據 data: { name: 'Tom', age: 18 } }).then(res => { // 插入數據成功 console.log(res) }).catch(err => { // 插入數據失敗 console.log(err) })
注意:spa
插入數據庫的數據爲額外有兩個id:_id(數據的主鍵id),_openid(這條數據的建立者的openid);code
直接從雲數據庫控制檯插入的數據是沒有openid的blog
2. 查詢操做rem
// where 查詢操做 db.collection('user').where({ // 查詢條件 name: 'Tom' }) .get() .then(res => { // 查詢數據成功 console.log(res) }).catch(err => { // 查詢數據失敗 console.log(err) })
3. 更新操做get
// update 更新操做 // primary key 要更新的那條數據的主鍵id db.collection('user').doc('primary key') .update({ // 想要更新後的數據 data: { age: 20 } }).then(res => { // 更新數據成功 console.log(res) }).catch(err => { // 更新數據失敗 console.log(err) })
4. 刪除操做io
// remove 刪除操做 // primary key 要刪除的那條數據的主鍵id db.collection('user').doc('primary key') .remove() .then(res => { // 刪除數據成功 console.log(res) }).catch(err => { // 刪除數據失敗 console.log(err) })
注意:此方法只適用於一次刪除一條數據,若想實現批量刪除數據,則要使用雲函數console