學(xué)習(xí)微信小程序 -- 數(shù)據(jù)庫
數(shù)據(jù)庫
1. 初始化
2. 數(shù)據(jù)庫操作
2.1 數(shù)據(jù)類型云開發(fā)數(shù)據(jù)庫提供以下幾種數(shù)據(jù)類型:
2.2 增刪查改
? ? ? ? ? ? ? ? ?2.2.1 增加/插入 數(shù)據(jù)(add方法)
? ? ? ? ? ? ? ? ?2.2.2 刪除數(shù)據(jù)(remove方法)
? ? ? ? ? ? ? ? ?2.2.3 查看數(shù)據(jù)(get,where)
? ? ? ? ? ? ? ? ?2.2.4 更新數(shù)據(jù)(update / set)
3. 云函數(shù)
數(shù)據(jù)庫
1. 初始化
查看官方文檔:開發(fā)指引 -> 數(shù)據(jù)庫 -> 增刪改查 ->?初始化.
第一步:?獲取數(shù)據(jù)庫的引用?(要操作一個(gè)集合,需先獲取它的引用。)
在開始使用數(shù)據(jù)庫 API 進(jìn)行增刪改查操作之前,需要先獲取數(shù)據(jù)庫的引用(兩種情況)。
-
以下調(diào)用獲取?默認(rèn)環(huán)境?的數(shù)據(jù)庫的引用:
const db = wx.cloud.database();
- 如需獲取?其他環(huán)境?的數(shù)據(jù)庫引用,可以在調(diào)用時(shí)傳入一個(gè)對(duì)象參數(shù),在其中通過 env 字段指定要使用的環(huán)境。此時(shí)方法會(huì)返回一個(gè)對(duì)測試環(huán)境數(shù)據(jù)庫的引用。
示例:假設(shè)有一個(gè)環(huán)境名為 test,用做測試環(huán)境,那么可以如下獲取測試環(huán)境數(shù)據(jù)庫:const testDB = wx.cloud.database({ env: 'test' })
第二步:數(shù)據(jù)庫里創(chuàng)建集合打開控制臺(tái),選擇 “數(shù)據(jù)庫” 標(biāo)簽頁,通過 “添加集合” 入口創(chuàng)建一個(gè)集合。假設(shè)我們要?jiǎng)?chuàng)建一個(gè)待辦事項(xiàng)小程序,我們創(chuàng)建一個(gè)名為 todos 的集合。創(chuàng)建成功后,可以看到 todos 集合管理界面,界面中我們可以添加記錄、查找記錄、管理索引和管理權(quán)限。集合 類似于 數(shù)據(jù)庫
? ? ?集合 類似于 數(shù)據(jù)庫
? ? ?集合里的記錄 相當(dāng)于 數(shù)據(jù)庫里的表
第三步:操作集合
在獲取了數(shù)據(jù)庫的引用后,就可以通過數(shù)據(jù)庫引用上的?collection
?方法獲取一個(gè)集合的引用了
- 比如獲取待辦事項(xiàng)清單集合:
const todos = db.collection('todos') // 'todos' 中的 todos 是集合名
獲取集合的引用并不會(huì)發(fā)起網(wǎng)絡(luò)請(qǐng)求去拉取它的數(shù)據(jù),我們可以通過此引用在該集合上進(jìn)行?增刪查改?的操作。除此之外,還可以通過集合上的?doc 方法?來獲取?集合中的一個(gè)指定 ID 的記錄的引用。同理,記錄的引用可以用于對(duì)特定記錄進(jìn)行更新和刪除操作。
? ? 2.假設(shè)我們有一個(gè)待辦事項(xiàng)的 ID 為 todo-identifiant-aleatoire,那么我們可以通過?doc
?方法獲取? ? ? 它的引用:
const todo = db.collection('todos').doc('todo-identifiant-aleatoire')
2. 數(shù)據(jù)庫操作
2.1 數(shù)據(jù)類型
云開發(fā)數(shù)據(jù)庫提供以下幾種數(shù)據(jù)類型:
String:字符串
Number:數(shù)字
Object:對(duì)象
Array:數(shù)組
Bool:布爾值
Date:時(shí)間
需要特別注意的是,在小程序端創(chuàng)建的時(shí)間是 客戶端時(shí)間,不是服務(wù)端時(shí)間,這意味著在小程序端的時(shí)間與服務(wù)端時(shí)間不一定吻合,如果需要使用服務(wù)端時(shí)間,應(yīng)該用 API 中提供的 serverDate 對(duì)象來創(chuàng)建一個(gè)服務(wù)端當(dāng)前時(shí)間的標(biāo)記
Geo:多種地理位置類型,詳見官方文檔
Null:相當(dāng)于一個(gè)占位符,表示一個(gè)字段存在但是值為空。
2.2 增刪查改
2.2.1 增加/插入 數(shù)據(jù)(add方法)
可以通過在集合對(duì)象上調(diào)用 add 方法往集合中插入一條記錄。
新增一個(gè)待辦事項(xiàng)官方代碼示例:
?
-
回調(diào)風(fēng)格調(diào)用
db.collection('todos').add({ // data 字段表示需新增的 JSON 數(shù)據(jù) data: { // _id: 'todo-identifiant-aleatoire', // 可選自定義 _id,在此處場景下用數(shù)據(jù)庫自動(dòng)分配的就可以了 description: "learn cloud database", due: new Date("2018-09-01"), tags: [ "cloud", "database" ], // 為待辦事項(xiàng)添加一個(gè)地理位置(113°E,23°N) location: new db.Geo.Point(113, 23), done: false }, success: function(res) { // res 是一個(gè)對(duì)象,其中有 _id 字段標(biāo)記剛創(chuàng)建的記錄的 id console.log(res) } })
- 在創(chuàng)建成功之后,我們可以在控制臺(tái)中查看到剛新增的數(shù)據(jù)。
- 可以在?add API 文檔?中查閱完整的 API 定義。
- 練習(xí)代碼(Promise 風(fēng)格)
addData(){ db.collection('js06').add({ // data 字段表示需新增的 JSON 數(shù)據(jù) data: { name:"gao", age:"23", sex:"女" }, }).then(res => { console.log(res) }); },
2.2.2 刪除數(shù)據(jù)(remove方法)
查看?刪除數(shù)據(jù)-官方文檔
- 刪除一條記錄
對(duì)記錄使用?remove
?方法可以刪除該條記錄,代碼示例:// 刪除數(shù)據(jù) deleteData(){ // doc后面是 指定刪除 那條的 id 記得:不是_openid哈 db.collection('js06').doc('ab79f8175ee716a500159a000bc74b18').remove({ success: function(res) { console.log(res.data) } }) }, // 或像下面這樣寫,比較舒爽一些 deleteData(){ db.collection('js06').doc('ab79f8175ee716a500159a000bc74b18') .remove() .then(res => { console.log(res); }); },
- 刪除多條記錄
如果需要更新多個(gè)數(shù)據(jù),需在 Server 端進(jìn)行操作(云函數(shù))??赏ㄟ^ where 語句選取多條記錄執(zhí)行刪除,只有有權(quán)限刪除的記錄會(huì)被刪除。比如刪除所有已完成的待辦事項(xiàng):
2.2.3 查看數(shù)據(jù)(get,where)
?查看?查看數(shù)據(jù)-官方文檔
- 獲取一個(gè)記錄的數(shù)據(jù)
假設(shè)已有一個(gè) ID 為 todo-identifiant-aleatoire 的在集合 todos 上的記錄,則可以通過在該記錄的引用調(diào)用?get
?方法獲取這個(gè)待辦事項(xiàng)的數(shù)據(jù):
db.collection('todos').doc('todo-identifiant-aleatoire').get({
success: function(res) {
// res.data 包含該記錄的數(shù)據(jù)
console.log(res.data)
}
})
也可以用 Promise 風(fēng)格調(diào)用:
db.collection('todos').doc('todo-identifiant-aleatoire').get().then(res => {
// res.data 包含該記錄的數(shù)據(jù)
console.log(res.data)
})
2.獲取多個(gè)記錄
我們也可以一次性獲取多條記錄。通過調(diào)用集合上的?where
?方法可以指定查詢條件,再調(diào)用 get 方法即可只返回滿足指定查詢條件的記錄,比如獲取用戶的所有未完成的待辦事項(xiàng):
db.collection('todos').where({
_openid: 'user-open-id',
done: false
})
.get({
success: function(res) {
// res.data 是包含以上定義的兩條記錄的數(shù)組
console.log(res.data)
}
})
3.查詢指令
假設(shè)我們需要查詢進(jìn)度大于 30% 的待辦事項(xiàng),那么傳入對(duì)象表示全等匹配的方式就無法滿足了,這時(shí)就需要用到查詢指令。數(shù)據(jù)庫 API 提供了大于、小于等多種查詢指令,這些指令都暴露在 db.command 對(duì)象上。比如查詢進(jìn)度大于 30% 的待辦事項(xiàng):
const _ = db.command
db.collection('todos').where({
// gt 方法用于指定一個(gè) "大于" 條件,此處 _.gt(30) 是一個(gè) "大于 30" 的條件
progress: _.gt(30)
})
.get({
success: function(res) {
console.log(res.data)
}
})
API 提供了以下查詢指令:
2.2.4 更新數(shù)據(jù)(update / set)
查看?更新數(shù)據(jù)-官方文檔
更新數(shù)據(jù)主要有兩個(gè)方法:
1.代碼練習(xí)
// 更新數(shù)據(jù)
updateData(){
db.collection('js06').doc('ab79f8175ee716a500159a000bc74b18').update({
// data 傳入需要局部更新的數(shù)據(jù)
data: {
// 表示將 done 字段置為 true
// done: true
age:_.gt(15),
name: "高"
}
}).then(res => {
console.log(res);
});
},
// 更新數(shù)據(jù) 回調(diào)風(fēng)格如下 使用success ,會(huì)輸出undefined,所以還是用.then舒服點(diǎn)
// updateData(){
// db.collection('js06').doc('ab79f8175ee716a500159a000bc74b18').update({
// // data 傳入需要局部更新的數(shù)據(jù)
// data: {
// name: "高"
// },
// success: function(res) {
// console.log(res.data)
// }
// })
// },
?2.set 與 update 的區(qū)別
set 指令的用處在于更新一個(gè)字段值為另一個(gè)對(duì)象。
比如如下語句是更新 style.color 字段為 ‘blue’ 而不是把 style 字段更新為 { color: ‘blue’ } 對(duì)象:
const _ = db.command
db.collection('todos').doc('todo-identifiant-aleatoire').update({
data: {
style: {
color: 'blue'
}
},
success: function(res) {
console.log(res.data)
}
})
?如果需要將這個(gè) style 字段更新為另一個(gè)對(duì)象,可以使用 set 指令:
const _ = db.command
db.collection('todos').doc('todo-identifiant-aleatoire').update({
data: {
style: _.set({
color: 'blue'
})
},
success: function(res) {
console.log(res.data)
}
})
3. 云函數(shù)
查看?云函數(shù)-官方文檔
云函數(shù)是一段運(yùn)行在云端的代碼,無需管理服務(wù)器,在開發(fā)工具內(nèi)編寫、一鍵上傳部署即可運(yùn)行后端代碼。
小程序內(nèi)提供了專門用于云函數(shù)調(diào)用的 API。開發(fā)者可以在云函數(shù)內(nèi)使用 wx-server-sdk 提供的 getWXContext 方法獲取到每次調(diào)用的上下文(appid、openid 等),無需維護(hù)復(fù)雜的鑒權(quán)機(jī)制,即可獲取天然可信任的用戶登錄態(tài)(openid)。
比如我們?nèi)缦露x一個(gè)云函數(shù),命名為 add ,功能是將傳入的兩個(gè)參數(shù) a 和 b 相加:
// index.js 是入口文件,云函數(shù)被調(diào)用時(shí)會(huì)執(zhí)行該文件導(dǎo)出的 main 方法
// event 包含了調(diào)用端(小程序端)調(diào)用該函數(shù)時(shí)傳過來的參數(shù),同時(shí)還包含了可以通過 getWXContext 方法獲取的用戶登錄態(tài) `openId` 和小程序 `appId` 信息
const cloud = require('wx-server-sdk')
exports.main = (event, context) => {
let { userInfo, a, b} = event
let { OPENID, APPID } = cloud.getWXContext() // 這里獲取到的 openId 和 appId 是可信的
let sum = a + b
return {
OPENID,
APPID,
sum
}
}
在開發(fā)者工具中上傳部署云函數(shù)后,我們?cè)谛〕绦蛑锌梢赃@么調(diào)用:
除了部署云函數(shù)進(jìn)行調(diào)用外,我們還支持云函數(shù)本地調(diào)試,可以不用部署云函數(shù)即可測試
wx.cloud.callFunction({
// 需調(diào)用的云函數(shù)名
name: 'add',
// 傳給云函數(shù)的參數(shù)
data: {
a: 12,
b: 19,
},
// 成功回調(diào)
complete: console.log
})
// 當(dāng)然 promise 方式也是支持的
wx.cloud.callFunction({
name: 'add',
data: {
a: 12,
b: 19
}
}).then(console.log)
如需在云函數(shù)中操作數(shù)據(jù)庫、管理云文件、調(diào)用其他云函數(shù)等操作,可使用官方提供的 npm 包 wx-server-sdk 進(jìn)行操作。文章來源:http://www.zghlxwxcb.cn/news/detail-776154.html
代碼練習(xí)文章來源地址http://www.zghlxwxcb.cn/news/detail-776154.html
// 云函數(shù)入口文件
const cloud = require('wx-server-sdk')
cloud.init();
// 記得下面這兩步
const db = cloud.database()
const _ = db.command
// 記得右鍵index.js文件更新?。。?
// 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
try{
return await db.collection('js06').where({ //寫條件查找~
age:_.gt(15) //記得在該文件前面 定義一下 db 和 _
})
.update({ //可執(zhí)行不同操作
data:{ //沒有的話新增,有的話是修改
height:"187cm"
},
})
}catch(e){
console.error(e)
}
// const wxContext = cloud.getWXContext()
// return {
// event,
// name:"張三"
// }
}
// 云函數(shù)的調(diào)用
// 有些像ajax(但不是哈)
updateiCloudData(){
wx.cloud.callFunction({
name: 'updateData', // 寫的是package.json里的name名
data: {
a: 10,
b: 20
}
}).then(res => {
console.log(res);
})
},
到了這里,關(guān)于微信小程序筆記--數(shù)據(jù)庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!