← Back to list

用 Firebase 建立 Serverless 網頁應用:從零到部署-Cloud Firestore

參考上一篇文章建立資料庫後會得到以下畫面:

Edgar · 2025-01-08 01:18 · 0 claps · 5.3 min read
#firebase #firestore
Open on Medium ↗
Wiki topics: ☁️ · DevOps & Cloud

用 Firebase 建立 Serverless 網頁應用:從零到部署-Cloud Firestore

Image Source: Google

Image Source: Google

參考上一篇文章建立資料庫後會得到以下畫面:

資料表畫面

資料表畫面

介面結構

文件 (Document)

  • 文件是 Cloud Firestore 中的基本單位,儲存以鍵-值對形式存在的結構化數據。
  • 每個文件都有一個唯一的 ID。
  • 文件可以包含:
  • 基本數據類型(字串、數字、布林值等)。
  • 嵌套物件(JSON 結構)。
  • 陣列(Array)。
  • 引用(對其他文件的引用)。

集合 (Collection)

  • 集合是文件的容器,可以包含多個文件。
  • 集合不能直接存儲數據,所有數據都存儲在文件中。
  • 集合與文件可以層次化嵌套(例如,一個文件可以包含子集合)。

根集合與子集合

  • 根集合:直接存儲於數據庫頂層的集合。
  • 子集合:存儲於文件中的集合,構建更細粒度的層次結構。

簡單資料對接

// Firebase 已初始化後使用
import { getFirestore, querySnapshot, onSnapshot } from "firebase/firestore";
const db = getFirestore();
const usersRef = collection(db, "users");

// 新增資料
usersRef("users").add({
  name: "John Doe",
  age: 25,
  email: "john.doe@example.com"
}).then((docRef) => {
  console.log("Document written with ID: ", docRef.id);
}).catch((error) => {
  console.error("Error adding document: ", error);
});

// 監聽資料
onSnapshot(usersRef, (snapshot) => {
  const addList = snapshot.docChanges() || [];
  addList.forEach(async (change: any) => {
    if (change.type === "added") {
      // 新增的資料
      console.log(`${change.doc.id} => ${change.doc.data()}`);
    }
  });
});

// 資料排序
const usersQuery = query(commentsRef, orderBy("age", "desc"));
const querySnapshot = await getDocs(
  usersQuery
);

// 取得資料列表
const userList = querySnapshot.docs
  .map((doc) => {
    if (doc.exists()) {
      const data = doc.data();
      return data;
    }
    return null;
  })

更多資訊可參考 官方文件

Firebase Storage

對於小型專案來說,Firebase Storage 結合 Firebase SDK 的易用性與即時性,能夠更輕鬆地整合到應用中。

到 Firebase Console 下方有可以開啟 Storage 的功能,成功開啟後左方側邊欄會有顯示標籤

到 Firebase Console 下方有可以開啟 Storage 的功能,成功開啟後左方側邊欄會有顯示標籤

開啟這個 API 需加入 Blaze 隨用隨付方案,雖然可設定預算,但快超過時只會通知不會立即停止流量計算,所以大專案或者怕會超出預算的人可能要考慮一下這點~

後台示意,可建立資料夾讓你在視覺上更方便地組織檔案。

後台示意,可建立資料夾讓你在視覺上更方便地組織檔案。

環境設定

資料庫位置可選擇 US-West1 離台灣比較近,存取規則方面因我只開放 Read ,如果想要其他規則可以自行修改。

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read: if true;
      allow write: if false;
    }
  }
}

前端獲取範例:

**詳細文檔請參考**

import { getStorage, ref, listAll, getDownloadURL } from "firebase/storage";

const storage = getStorage();
const listRef = ref(storage, 'images'); // 例如您要列出 'images' 資料夾下的所有檔案

listAll(listRef)
  .then((res) => {
    res.items.forEach((itemRef) => {
      getDownloadURL(itemRef)
        .then((url) => {
          // 這裡可以動態產生 <img> 元素或以其他方式使用該圖片 URL
          console.log(url);
        })
        .catch((error) => {
          console.error("取得圖片失敗:", error);
        });
    });
  })
  .catch((error) => {
    console.error("列出資料夾失敗:", error);
  });

根據需求做延遲載入(lazy loading)或分頁處理。

結語

Cloud Firestore 作為 Firebase 生態中的關鍵服務,無論是簡單的 CRUD 操作,還是複雜的查詢與交易處理,Cloud Firestore 都能提供解決方案。

希望本文的介紹能讓您對 Cloud Firestore 初步的認識,也能啟發您將其應用於您的專案中,實現更高效、更穩定的資料管理。


메타데이터
post_id
441cbc2cea49
slug
用-firebase-建立-serverless-網頁應用-從零到部署-cloud-firestore-441cbc2cea49
url
https://medium.com/@73307hank/%E7%94%A8-firebase-%E5%BB%BA%E7%AB%8B-serverless-%E7%B6%B2%E9%A0%81%E6%87%89%E7%94%A8-%E5%BE%9E%E9%9B%B6%E5%88%B0%E9%83%A8%E7%BD%B2-cloud-firestore-441cbc2cea49
canonical_url
https://medium.com/@73307hank/%E7%94%A8-firebase-%E5%BB%BA%E7%AB%8B-serverless-%E7%B6%B2%E9%A0%81%E6%87%89%E7%94%A8-%E5%BE%9E%E9%9B%B6%E5%88%B0%E9%83%A8%E7%BD%B2-cloud-firestore-441cbc2cea49
author_url
https://medium.com/@73307hank
status
ok
fetched_at
2026-07-21 09:41:57