W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
在開始使用數(shù)據(jù)庫(kù) API 進(jìn)行增刪改查操作之前,需要先獲取數(shù)據(jù)庫(kù)的引用。以下調(diào)用獲取默認(rèn)環(huán)境的數(shù)據(jù)庫(kù)的引用:
const db = qq.cloud.database()
如需獲取其他環(huán)境的數(shù)據(jù)庫(kù)引用,可以在調(diào)用時(shí)傳入一個(gè)對(duì)象參數(shù),在其中通過 env 字段指定要使用的環(huán)境。此時(shí)方法會(huì)返回一個(gè)對(duì)測(cè)試環(huán)境數(shù)據(jù)庫(kù)的引用。 示例:假設(shè)有一個(gè)環(huán)境名為 test,用做測(cè)試環(huán)境,那么可以如下獲取測(cè)試環(huán)境數(shù)據(jù)庫(kù):
如需獲取其他環(huán)境的數(shù)據(jù)庫(kù)引用,可以在調(diào)用時(shí)傳入一個(gè)對(duì)象參數(shù),在其中通過 env 字段指定要使用的環(huán)境。此時(shí)方法會(huì)返回一個(gè)對(duì)測(cè)試環(huán)境數(shù)據(jù)庫(kù)的引用。 示例:假設(shè)有一個(gè)環(huán)境名為 test,用做測(cè)試環(huán)境,那么可以如下獲取測(cè)試環(huán)境數(shù)據(jù)庫(kù):
const testDB = qq.cloud.database({
env: 'test'
})
要操作一個(gè)集合,需先獲取它的引用。在獲取了數(shù)據(jù)庫(kù)的引用后,就可以通過數(shù)據(jù)庫(kù)引用上的 collection 方法獲取一個(gè)集合的引用了,比如獲取待辦事項(xiàng)清單集合:
const todos = db.collection('todos')
獲取集合的引用并不會(huì)發(fā)起網(wǎng)絡(luò)請(qǐng)求去拉取它的數(shù)據(jù),我們可以通過此引用在該集合上進(jìn)行增刪查改的操作,除此之外,還可以通過集合上的 doc 方法來獲取集合中一個(gè)指定 ID 的記錄的引用。同理,記錄的引用可以用于對(duì)特定記錄進(jìn)行更新和刪除操作。 假設(shè)我們有一個(gè)待辦事項(xiàng)的 ID 為 todo-identifiant-aleatoire,那么我們可以通過 doc 方法獲取它的引用:
const todo = db.collection('todos').doc('todo-identifiant-aleatoire')
示例代碼如下:
const tcb = require("tcb-admin-node");
// 初始化資源
// 云函數(shù)下不需要secretId和secretKey。
// env如果不指定將使用默認(rèn)環(huán)境
tcb.init({
secretId: 'xxxxx',
secretKey: 'xxxx',
env: 'xxx'
});
//云函數(shù)下使用默認(rèn)環(huán)境
tcb.init();
//云函數(shù)下指定環(huán)境
tcb.init({
env: 'xxx'
});
可以通過在集合對(duì)象上調(diào)用 add 方法往集合中插入一條記錄。還是用待辦事項(xiàng)清單的例子,比如我們想新增一個(gè)待辦事項(xiàng)
示例代碼如下:
const db = qq.cloud.database();
db.collection('todos').add({
// data 字段表示需新增的 JSON 數(shù)據(jù)
data: {
// _id: 'todo-identifiant-aleatoire', // 可選自定義 _id,在此處場(chǎng)景下用數(shù)據(jù)庫(kù)自動(dòng)分配的就可以了
description: "learn cloud database",
due: new Date("2018-09-01"),
tags: [
"cloud",
"database"
],
// 為待辦事項(xiàng)添加一個(gè)地理位置
location: new db.Geo.Point(23, 113),
done: false
},
})
.then(res => {
console.log(res)
})
.catch(console.error);
服務(wù)端
示例代碼如下:
const app = require('tcb-admin-node');
app.init();
const db = app.database();
db.collection('todos').add({
// _id: 'todo-identifiant-aleatoire', // 可選自定義 _id,在此處場(chǎng)景下用數(shù)據(jù)庫(kù)自動(dòng)分配的就可以了
description: "learn cloud database",
due: new Date("2018-09-01"),
tags: [
"cloud",
"database"
],
// 為待辦事項(xiàng)添加一個(gè)地理位置
location: new db.Geo.Point(23, 113),
done: false
})
.then(res => {
console.log(res)
})
.catch(console.error);
在創(chuàng)建成功之后,我們可以在控制臺(tái)中查看到剛新增的數(shù)據(jù)。 可以在 add API 文檔中查閱完整的 API 定義。
在記錄和集合上都有提供 get 方法用于獲取單個(gè)記錄或集合中多個(gè)記錄的數(shù)據(jù)。 假設(shè)我們已有一個(gè)集合 todos,其中包含以下格式記錄:
[
{
_id: 'todo-identifiant-aleatoire',
_openid: 'user-open-id', // 假設(shè)用戶的 openid 為 user-open-id
description: "learn cloud database",
due: Date("2018-09-01"),
progress: 20,
tags: [
"cloud",
"database"
],
style: {
color: 'white',
size: 'large'
},
location: Point(113.33, 23.33), // 113.33°E,23.33°N
done: false
},
{
_id: 'todo-identifiant-aleatoire-2',
_openid: 'user-open-id', // 假設(shè)用戶的 openid 為 user-open-id
description: "write a novel",
due: Date("2018-12-25"),
progress: 50,
tags: [
"writing"
],
style: {
color: 'yellow',
size: 'normal'
},
location: Point(113.22, 23.22), // 113.22°E,23.22°N
done: false
}
// more...
]
我們先來看看如何獲取一個(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().then(res => {
// res.data 包含該記錄的數(shù)據(jù)
console.log(res.data)
})
我們也可以一次性獲取多條記錄。通過調(diào)用集合上的 where 方法可以指定查詢條件,再調(diào)用 get 方法即可只返回滿足指定查詢條件的記錄,獲取用戶的所有未完成的待辦事項(xiàng)。示例代碼如下:
db.collection('todos').where({
_openid: 'user-open-id',
done: false
})
.get().then((res) => {
// res.data 是包含以上定義的兩條記錄的數(shù)組
console.log(res.data);
});
where 方法接收一個(gè)對(duì)象參數(shù),該對(duì)象中每個(gè)字段和它的值構(gòu)成一個(gè)需滿足的匹配條件,各個(gè)字段間的關(guān)系是 "與" 的關(guān)系,即需同時(shí)滿足這些匹配條件,在這個(gè)例子中,就是查詢出 todos 集合中 _openid 等于 user-open-id 且 done 等于 false 的記錄。在查詢條件中我們也可以指定匹配一個(gè)嵌套字段的值,找出自己的標(biāo)為黃色的待辦事項(xiàng):
db.collection('todos').where({
\_openid: 'user-open-id',
style: {
color: 'yellow'
}
})
.get().then((res) => {
console.log(res.data);
});
使用 "點(diǎn)表示法" 表示嵌套字段:
db.collection('todos').where({
_openid: 'user-open-id',
'style.color': 'yellow'
})
.get().then((res) => {
console.log(res.data);
});
如果要獲取一個(gè)集合的數(shù)據(jù),獲取 todos 集合上的所有記錄,可以在集合上調(diào)用 get 方法獲取,但通常不建議這么使用,在客戶端中我們需要盡量避免一次性獲取過量的數(shù)據(jù),只應(yīng)獲取必要的數(shù)據(jù)。為了防止誤操作以及保護(hù)用戶體驗(yàn),在獲取集合數(shù)據(jù)時(shí)服務(wù)器一次最多返回 20 條記錄。開發(fā)者可以通過 limit 方法指定需要獲取的記錄數(shù)量,但不能超過 20 條。
db.collection('todos').get().then((res) => {
// res.data 是一個(gè)包含集合中有權(quán)限訪問的所有記錄的數(shù)據(jù),不超過 20 條
console.log(res.data);
});
服務(wù)端: 服務(wù)端的數(shù)據(jù)獲取方法與客戶端大致相同,請(qǐng)參考以下示例:
const app = require('tcb-admin-node');
app.init();
const db = app.database();
// 獲取一個(gè)記錄的數(shù)據(jù)
db.collection('todos').doc('todo-identifiant-aleatoire').get().then((res) => {
// res.data 包含該記錄的數(shù)據(jù)
console.log(res.data);
});
// 獲取多個(gè)記錄的數(shù)據(jù)
db.collection('todos').where({
_openid: 'user-open-id',
done: false
})
.get().then((res) => {
// res.data 是包含以上定義的兩條記錄的數(shù)組
console.log(res.data);
});
// 獲取一個(gè)集合的數(shù)據(jù)
db.collection('todos').get().then((res) => {
// res.data 是一個(gè)包含集合中有權(quán)限訪問的所有記錄的數(shù)據(jù),不超過 20 條
console.log(res.data);
});
使用數(shù)據(jù)庫(kù) API 提供的 where 方法我們可以構(gòu)造復(fù)雜的查詢條件完成復(fù)雜的查詢?nèi)蝿?wù)。在本節(jié)中我們還是使用上一章節(jié)中使用的示例數(shù)據(jù)。
假設(shè)我們需要查詢進(jìn)度大于 30% 的待辦事項(xiàng),那么傳入對(duì)象表示全等匹配的方式就無法滿足了,這時(shí)就需要用到查詢指令。數(shù)據(jù)庫(kù) 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()
.then(res => {
console.log(res.data);
});
API 提供了以下查詢指令:
查詢指令 | 說明 |
---|---|
eq | 等于 |
neq | 不等于 |
lt | 小于 |
lte | 小于或等于 |
gt | 大于 |
gte | 大于或等于 |
in | 字段值在給定數(shù)組中 |
nin | 字段值不在給定數(shù)組中 |
除了指定一個(gè)字段滿足一個(gè)條件之外,我們還可以通過指定一個(gè)字段需同時(shí)滿足多個(gè)條件。 使用 and 邏輯指令查詢進(jìn)度在30%和70%之間的待辦事項(xiàng)。示例如下:
const _ = db.command
db.collection('todos').where({
// and 方法用于指定一個(gè) "與" 條件,此處表示需同時(shí)滿足 _.gt(30) 和 _.lt(70) 兩個(gè)條件
progress: _.gt(30).and(_.lt(70))
})
.get()
.then((res) => {
console.log(res.data);
});
使用 or 指令,查詢進(jìn)度為0或100的待辦事項(xiàng),示例如下:
const _ = db.command
db.collection('todos').where({
// or 方法用于指定一個(gè) "或" 條件,此處表示需滿足 _.eq(0) 或 _.eq(100)
progress: _.eq(0).or(_.eq(100))
})
.get().then((res) => {
console.log(res.data);
});
如需跨字段進(jìn)行 "或" 操作,您也可以使用or指令,or指令同時(shí)可以用來接受多個(gè)(可以多于兩個(gè))查詢條件,表示需滿足多個(gè)查詢條件中的任意一個(gè)。 查詢進(jìn)度小于或等于50%或顏色為白色或黃色的待辦事項(xiàng),示例如下:
const _ = db.command
db.collection('todos').where(_.or([
{
progress: _.lte(50)
},
{
style: {
color: _.in(['white', 'yellow'])
}
}
]))
.get()
.then((res) => {
console.log(res.data);
});
在這章節(jié)我們一起看看如何使用數(shù)據(jù)庫(kù) API 完成數(shù)據(jù)刪除,在本節(jié)中我們還是沿用讀取數(shù)據(jù)章節(jié)中使用的數(shù)據(jù)。
對(duì)記錄使用 remove 方法可以刪除該條記錄,示例代碼如下
db.collection('todos').doc('todo-identifiant-aleatoire').remove().then((res) => {
console.log(res.data);
});
如果需要更新多個(gè)數(shù)據(jù),需在 Server 端進(jìn)行操作(云函數(shù))??赏ㄟ^ where 語(yǔ)句選取多條記錄執(zhí)行刪除,僅有權(quán)限刪除的記錄會(huì)被刪除。例如刪除所有已完成的待辦事項(xiàng)。示例代碼如下:
// 使用了 async await 語(yǔ)法
const app = require('tcb-admin-node');
app.init();
const db = app.database();
const _ = db.command;
exports.main = async (event, context) => {
try {
return await db.collection('todos').where({
done: true
}).remove();
} catch(e) {
console.error(e);
}
}
注意: 在大多數(shù)情況下,您只能操作自己的數(shù)據(jù)(自己的代表事項(xiàng)),不能操作其他人的數(shù)據(jù)(其他人的待辦事項(xiàng)),如需操作他人數(shù)據(jù)需獲取更高權(quán)限。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: