Google - Cloud Firestore 數據的寫入讀取

Cloud Firestore 是 Google 提供的即時資料庫,可即時監聽資料庫的變化,並同步使用各個應用。

數據結構

在 Cloud Firestore 中構建數據時,分為集合( collection ) 與文件 ( doc ) ,集合包含著文件,文件裡還可包含著子集合,而數據資料只能存在文件上。

寫入資料

set (設定)

可設定在指定集合裡添加文件並寫入資料。( 可指定 doc 名稱 )
若沒有指定文件 doc 的名稱,會自動產生一個亂數代碼作為文件名稱。

1
2
3
4
5
6
7
8
9
10
let db = firebase.firestore();
let ref = db.collection("users").doc("frank");

ref.set({
name: "Frank",
favorites: { food: "Pizza", color: "Blue", subject: "recess" },
age: 12
}).then(() => {
console.log('set data successful');
});

merge 方法 : 進行合併整理,而不會覆蓋資料。

1
2
3
4
5
ref.set({
sex : 'Male'
},{merge:true}).then(() => {
console.log('set data successful');
});

add (添加)

add 可以自動添加文件,文件名稱為系統自動產生的亂碼。

1
2
3
4
5
6
7
8
db.collection("users").add({
first: "Alan",
middle: "Mathison",
last: "Turing",
born: 1912
}).then(() => {
console.log('set data successful');
});

update (更新)

對 doc 內某個屬性進行更新,避免覆寫整個文件內容。
更新下階子屬性使用 . 來做更新。

1
2
3
4
5
6
ref.update({
"age": 13,
"favorites.color": "Red"
}).then(() => {
console.log('set data successful');
});

delete (刪除)

用於刪除集合或是文件,但如果集合裡有文件,則無法刪除集合。

1
2
3
db.collection("users").doc('OS0t1rl9S9tpFtlve8H1').delete().then(() => {
console.log('delete data successful');
});
若想刪除文件內的某個屬性,則需要透過update的方式來實現。
1
2
3
4
5
ref.update({
sex: firebase.firestore.FieldValue.delete()
}).then(() => {
console.log('set data successful');
});
![](https://drive.google.com/uc?export=view&id=1YvOO7BlXUAngQkpR2cTxLywZtQ0SPlaQ)

讀取資料

有讀取 ( get ) 和即時監聽 ( onSnapshot ) 兩種方法,可以搭配篩選 ( where ) 和排序 ( orderBy ) 來進一步的篩選。

以下為範例資料庫數據:

get (取得資料)

取得集合裡,所有文件的資料,並使用 forEach 個別取出文件內容。

1
2
3
4
5
6
7
8
 let db = firebase.firestore();
let ref = db.collection("users");

ref.get().then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log(doc.id, doc.data());
});
});

指定文件的名稱,則直接取得文件內容。

1
2
3
4
5
let ref = db.collection("users").doc('ming');

ref.get().then(doc => {
console.log(doc.id, doc.data());
});

onSnapshot (即時監聽)

可以即時監聽資料庫的變化。

1
2
3
4
5
6
7
8
let db = firebase.firestore();
let ref = db.collection("users");

ref.onSnapshot(querySnapshot => {
querySnapshot.forEach(doc => {
console.log(doc.id, doc.data());
});
});

where (篩選)

進行資料篩選,包含三個參數,第一個是屬性名稱,第二個是邏輯運算子,第三個是屬性值。
邏輯運算子包含: <、<=、==、>、>=、!=、in ( 邏輯OR )、not-in ( 邏輯AND ) 。

1
2
3
4
5
6
7
8
let db = firebase.firestore();
let ref = db.collection("users");

ref.where('sex','==','Male').get().then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log(doc.id, doc.data());
});
});

orderBy (排序)

會和 limit (用於檢索文檔數量)搭配,作為排序後篩選特定數量的資料。
orderBy 有兩個參數,第一個是屬性名稱,第二個是遞增 ( asc ) 或遞減 ( desc ) 。

1
2
3
4
5
ref.orderBy('age','desc').limit(3).get().then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log(doc.id, doc.data());
});
});

作者

LeeU

發表於

2020-12-17

更新於

2023-04-03

許可協議