先初始化資料庫
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) })
注意:
插入資料庫的資料為額外有兩個id:_id(資料的主鍵id),_openid(這條資料的創建者的openid);
直接從云資料庫控制臺插入的資料是沒有openid的
2. 查詢操作
// where 查詢操作 db.collection('user').where({ // 查詢條件 name: 'Tom' }) .get() .then(res => { // 查詢資料成功 console.log(res) }).catch(err => { // 查詢資料失敗 console.log(err) })
3. 更新操作
// 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. 洗掉操作
// remove 洗掉操作 // primary key 要洗掉的那條資料的主鍵id db.collection('user').doc('primary key') .remove() .then(res => { // 洗掉資料成功 console.log(res) }).catch(err => { // 洗掉資料失敗 console.log(err) })
注意:此方法只適用于一次洗掉一條資料,若想實作批量洗掉資料,則要使用云函式,如下
5. 使用云函式批量洗掉資料
5.1 新建云函式(batchDelete),在云函式的入口檔案中
// 云函式入口檔案 const cloud = require('wx-server-sdk') // 初始化云資料庫 const db = wx.cloud.database() cloud.init() // 云函式入口函式 exports.main = async (event, context) => { try { // 找到集合user中name為Tom的資料并remove洗掉 // 因為資料庫洗掉是異步操作,所以要加await return await db.collection('user').where({ name: 'jane' }).remove() } catch (err) { console.error(err) } }
注意:云函式創建或有任何修改后,都需要手動部署到云端后才可生效
5.2 在page的js中呼叫這個云函式
// callFunction 呼叫云函式 wx.cloud.callFunction({ // 云函式名稱 name: 'batchDelete' }).then(res => { console.log(res) }).catch(err => { console.error(err) })
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/176005.html
標籤:JavaScript
下一篇:JavaScript的歷史
