本快速入門導覽課程說明如何設定 Firestore Enterprise 版、新增資料,然後使用核心作業或管道作業,在 Firebase 控制台查詢剛新增的資料。
Cloud Firestore 支援行動或網頁 SDK 和伺服器用戶端程式庫:
Cloud Firestore 支援 Android、iOS 和網頁等 SDK。搭配 Cloud Firestore Security Rules 和 Firebase Authentication,行動和網頁 SDK 支援無伺服器應用程式架構,用戶端可直接連線至 Cloud Firestore 資料庫。
Cloud Firestore 支援 Java、Node.js 和 Python 的伺服器用戶端程式庫。您可以使用這些用戶端程式庫,設定具備資料庫完整存取權的特殊權限伺服器環境。如要進一步瞭解這些程式庫,請參閱「伺服器用戶端程式庫快速入門導覽課程」。
AI 輔助功能的 AI 提示
如需 AI 輔助,請將下方提示詞複製到 AI 程式設計代理 (例如 Android Studio 內建 Gemini、Antigravity、Claude Code、Codex 和 Cursor)。您可以自訂提示,並與代理反覆調整。如需詳細安裝資訊,請參閱 Firebase 代理技能。
Help me use Firebase in my app.
1. Make sure that **Firebase agent skills** are installed and updated. For Claude Code, Codex, or Cursor agents, help me install the Firebase plugin. For other agents, run `npx skills add firebase/agent-skills`. Always try to use **Firebase agent skills** for Firebase-related tasks.
2. Help me set up and use Firebase for the backend of my app. Set up Firestore database in **Enterprise edition**. Help me to choose the best location for my database instance.
建立 Firestore Enterprise 版資料庫
如果您尚未建立 Firebase 專案,請前往 Firebase 控制台,按一下「Add project」(新增專案),然後按照畫面上的指示建立 Firebase 專案,或將 Firebase 服務新增至現有的 Google Cloud 專案。
在左側面板中,依序前往「Databases & Storage」(資料庫和儲存空間) > 「Firestore」。
按一下 [Create database] (建立資料庫)。
資料庫模式請選取「Enterprise」。
選取「Firestore in Native Mode」(Firestore 原生模式) 做為作業模式,此模式支援核心和管道作業。
選取資料庫的位置。
選取Cloud Firestore Security Rules的起始模式:
- 測試模式
適合用於開始使用行動和網路用戶端程式庫,但任何人都能讀取及覆寫您的資料。測試完成後,請務必詳閱「保護資料」一節。
如要開始使用網頁、Apple 平台或 Android SDK,請選取測試模式。
- 正式環境模式
拒絕所有來自行動和網路用戶端的讀寫要求。通過驗證的應用程式伺服器 (Python) 仍可存取資料庫。
初始 Cloud Firestore Security Rules 組合會套用至預設 Cloud Firestore 資料庫。如果您為專案建立多個資料庫,可以為每個資料庫部署 Cloud Firestore Security Rules。
點選「建立」。
啟用 Firestore Enterprise 版時,系統也會在 Cloud API Manager 中啟用 API。
設定開發環境
將必要的依附元件和用戶端程式庫新增至應用程式。
Web
- 按照操作說明將 Firebase 新增至網頁應用程式。
-
Cloud Firestore SDK 以 npm 套件的形式提供。
您必須同時匯入 Firebase 和 Cloud Firestore。npm install firebase@13.2.0 --save
import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore";
iOS+
按照操作說明將 Firebase 新增至 Apple 應用程式。
使用 Swift Package Manager 安裝及管理 Firebase 依附元件。
- 在 Xcode 中保持應用程式專案開啟,然後依序點選「File」>「Swift Packages」>「Add Package Dependency」。
- 系統提示時,請新增 Firebase Apple 平台 SDK 存放區:
- 選擇 Firestore 程式庫。
- 完成後,Xcode 會自動開始在背景解析及下載依附元件。
https://github.com/firebase/firebase-ios-sdk
Android
- 按照操作說明將 Firebase 新增至 Android 應用程式。
- 使用 Firebase Android BoM,在模組 (應用程式層級) Gradle 檔案 (通常是
app/build.gradle.kts或app/build.gradle) 中,宣告 Cloud Firestore Android 程式庫的依附元件。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:35.1.0")) // Declare the dependency for the Cloud Firestore library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-firestore") }
只要使用 Firebase Android BoM,應用程式就會一律使用相容的 Firebase Android 程式庫版本。
(替代做法) 宣告 Firebase 程式庫依附元件,不使用 BoM
如果選擇不使用 Firebase BoM,則必須在依附元件行中指定每個 Firebase 程式庫版本。
請注意,如果您的應用程式使用多個 Firebase 程式庫,強烈建議您使用 BoM 管理程式庫版本,確保所有版本都相容。
dependencies { // Declare the dependency for the Cloud Firestore library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-firestore:27.1.0") }
想尋找 Kotlin 專屬程式庫模組嗎?自 2023 年 10 月版本起,Kotlin 和 Java 開發人員都可以依附主要程式庫模組 (詳情請參閱這項計畫的常見問題)。
初始化 Cloud Firestore
初始化 Cloud Firestore 的例項:
Web
import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore"; // TODO: Replace the following with your app's Firebase project configuration // See: https://support.google.com/firebase/answer/7015592 const firebaseConfig = { FIREBASE_CONFIGURATION }; // Initialize Firebase const app = initializeApp(firebaseConfig); // When initializing Firestore, remember to use the name of the database you created earlier: const db = initializeFirestore(app, {}, 'your-new-enterprise-database');
將 FIREBASE_CONFIGURATION 替換為網頁應用程式的firebaseConfig。
如要在裝置連線中斷時保留資料,請參閱「啟用離線資料」說明文件。
Swift
import FirebaseCore import FirebaseFirestore FirebaseApp.configure() // When initializing Firestore, remember to use the name of the database you created earlier: let db = Firestore.firestore(database: "your-new-enterprise-database")
Kotlin
// Access a Cloud Firestore instance from your Activity // When initializing Firestore, remember to use the name of the database you created earlier: val firestore = FirebaseFirestore.getInstance("your-new-enterprise-database")
Java
// Access a Cloud Firestore instance from your Activity // When initializing Firestore, remember to use the name of the database you created earlier: FirebaseFirestore firestore = FirebaseFirestore.getInstance("your-new-enterprise-database");
使用核心作業新增資料
如要探索核心作業和管道作業,以便查詢資料,請使用核心作業將資料新增至資料庫。
Cloud Firestore 會將資料儲存在文件中,而文件則儲存在集合中。首次將資料新增至文件時,Cloud Firestore 會隱含建立集合和文件。您不需要明確建立集合或文件。
使用下列範例程式碼建立新的集合和文件。
Web
import { collection, addDoc } from "firebase/firestore"; try { const docRef = await addDoc(collection(db, "users"), { first: "Ada", last: "Lovelace", born: 1815 }); console.log("Document written with ID: ", docRef.id); } catch (e) { console.error("Error adding document: ", e); }
Web
db.collection("users").add({ first: "Ada", last: "Lovelace", born: 1815 }) .then((docRef) => { console.log("Document written with ID: ", docRef.id); }) .catch((error) => { console.error("Error adding document: ", error); });
Swift
// Add a new document with a generated ID do { let ref = try await db.collection("users").addDocument(data: [ "first": "Ada", "last": "Lovelace", "born": 1815 ]) print("Document added with ID: \(ref.documentID)") } catch { print("Error adding document: \(error)") }
Kotlin
// Create a new user with a first and last name val user = hashMapOf( "first" to "Ada", "last" to "Lovelace", "born" to 1815, ) // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener { documentReference -> Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}") } .addOnFailureListener { e -> Log.w(TAG, "Error adding document", e) }
Java
// Create a new user with a first and last name Map<String, Object> user = new HashMap<>(); user.put("first", "Ada"); user.put("last", "Lovelace"); user.put("born", 1815); // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } });
現在,請將另一份文件新增至 users 集合。請注意,這份文件包含第一個文件中未出現的鍵/值組合 (中間名)。集合中的文件可以包含不同的資訊組合。
Web
// Add a second document with a generated ID. import { addDoc, collection } from "firebase/firestore"; try { const docRef = await addDoc(collection(db, "users"), { first: "Alan", middle: "Mathison", last: "Turing", born: 1912 }); console.log("Document written with ID: ", docRef.id); } catch (e) { console.error("Error adding document: ", e); }
Web
// Add a second document with a generated ID. db.collection("users").add({ first: "Alan", middle: "Mathison", last: "Turing", born: 1912 }) .then((docRef) => { console.log("Document written with ID: ", docRef.id); }) .catch((error) => { console.error("Error adding document: ", error); });
Swift
// Add a second document with a generated ID. do { let ref = try await db.collection("users").addDocument(data: [ "first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912 ]) print("Document added with ID: \(ref.documentID)") } catch { print("Error adding document: \(error)") }
Kotlin
// Create a new user with a first, middle, and last name val user = hashMapOf( "first" to "Alan", "middle" to "Mathison", "last" to "Turing", "born" to 1912, ) // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener { documentReference -> Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}") } .addOnFailureListener { e -> Log.w(TAG, "Error adding document", e) }
Java
// Create a new user with a first, middle, and last name Map<String, Object> user = new HashMap<>(); user.put("first", "Alan"); user.put("middle", "Mathison"); user.put("last", "Turing"); user.put("born", 1912); // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } });
使用核心作業讀取資料
使用 Firebase 控制台中的資料檢視器,快速確認您已將資料新增至 Cloud Firestore。
您也可以使用「get」方法擷取整個集合。
Web
import { collection, getDocs } from "firebase/firestore"; const querySnapshot = await getDocs(collection(db, "users")); querySnapshot.forEach((doc) => { console.log(doc.id, "=>", doc.data()); });
Web
db.collection("users").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(doc.id, "=>", doc.data()); }); });
Swift
do { let snapshot = try await db.collection("users").getDocuments() for document in snapshot.documents { print("\(document.documentID) => \(document.data())") } } catch { print("Error getting documents: \(error)") }
Kotlin
db.collection("users") .get() .addOnSuccessListener { result -> for (document in result) { Log.d(TAG, "${document.id} => ${document.data}") } } .addOnFailureListener { exception -> Log.w(TAG, "Error getting documents.", exception) }
Java
db.collection("users") .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { Log.d(TAG, document.getId() + " => " + document.getData()); } } else { Log.w(TAG, "Error getting documents.", task.getException()); } } });
使用管道作業讀取資料
現在,您可以比較 Pipeline 查詢體驗與 Core 查詢體驗。
Web
// The import/require of "firebase/firestore/pipelines" has a side-effect // of extending the Firestore class with the `.pipeline()` method. // Without this import/require, you will not be able to create a Pipeline. // import { execute } from "firebase/firestore/pipelines"; const readDataPipeline = db.pipeline() .collection("users"); // Execute the pipeline and handle the result try { const querySnapshot = await execute(readDataPipeline); querySnapshot.results.forEach((result) => { console.log(`${result.id} => ${result.data()}`); }); } catch (error) { console.error("Error getting documents: ", error); }
Swift
do { // Initialize a Firestore Pipeline instance and specify the "users" collection as the // input stage. let snapshot = try await db.pipeline() .collection("users") .execute() // Execute the pipeline to retrieve documents. // Iterate through the documents in the pipeline results, similar to a regular query // snapshot. for result in snapshot.results { print("\(result.id ?? "no ID") => \(result.data)") } } catch { print("Error getting documents with pipeline: \(error)") }
Kotlin
val readDataPipeline = db.pipeline() .collection("users") // Execute the pipeline and handle the result readDataPipeline.execute() .addOnSuccessListener { result -> for (document in result) { println("${document.getId()} => ${document.getData()}") } } .addOnFailureListener { exception -> println("Error getting documents: $exception") }
Java
Pipeline readDataPipeline = db.pipeline() .collection("users"); readDataPipeline.execute() .addOnSuccessListener(new OnSuccessListener<Pipeline.Snapshot>() { @Override public void onSuccess(Pipeline.Snapshot snapshot) { for (PipelineResult result : snapshot.getResults()) { System.out.println(result.getId() + " => " + result.getData()); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { System.out.println("Error getting documents: " + e); } });
保護行動和網頁 SDK 的資料
如果您使用的是網頁、Android 或 Apple 平台 SDK,請使用 Firebase Authentication 和 Cloud Firestore Security Rules 保護 Cloud Firestore 中的資料。
以下是一些基本規則集,可協助您快速上手。如要修改安全性規則,請前往 Firebase 控制台,依序點選「資料庫和儲存空間」>「Firestore」>「規則」分頁標籤。
需要驗證
// Allow read/write access to a document keyed by the user's UID
service cloud.firestore {
match /databases/{database}/documents {
match /users/{uid} {
allow read, write: if request.auth != null && request.auth.uid == uid;
}
}
}
正式環境模式
// Deny read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
將網頁、Android 或 iOS 應用程式部署至正式環境前,請務必採取相關步驟,確保只有您的應用程式用戶端可以存取 Cloud Firestore 資料。請參閱 App Check 說明文件。
如果您使用其中一個伺服器 SDK,請透過 Identity and Access Management (IAM) 保護 Cloud Firestore 中的資料。
後續步驟
請參閱下列主題,進一步瞭解 Core 和 Pipeline 作業:
- 進一步瞭解如何使用核心作業查詢
- 進一步瞭解如何使用管道作業查詢。
- 瞭解如何強化 AI 開發工具,更有效率地執行工作,並運用 Firebase 代理技能,採用 Cloud Firestore 最佳做法 (例如編寫Cloud Firestore Security Rules)。