開始使用 Cloud Firestore

本快速入門導覽課程說明如何設定 Cloud Firestore、新增資料及查看 顯示剛才在 Firebase 控制台新增的資料

建立 Cloud Firestore 資料庫

  1. 如果您尚未建立 Firebase 專案,請先在 Firebase 控制台,按一下「新增專案」。 然後按照畫面上的指示建立 Firebase 專案,或是 將 Firebase 服務加入現有的 GCP 專案。

  2. 前往下列專案的「Cloud Firestore」部分: Firebase 控制台: 系統會提示您選取現有的 Firebase 專案。 按照資料庫建立工作流程操作。

  3. 選取 Cloud Firestore 安全性規則的啟動模式:

    測試模式

    適合入門至行動和網路用戶端程式庫 但允許所有人讀取及覆寫您的資料測試完畢後, 請務必詳閱「保護您的資料」一節。

    如要開始使用網站、Apple 平台或 Android SDK,請選取測試模式。

    鎖定模式

    拒絕所有來自行動和網路用戶端的讀寫作業。 您的驗證應用程式伺服器 (C#、Go、Java、Node.js、PHP Python 或 Ruby) 仍可存取您的資料庫。

    如何開始使用 C#、Go、Java、Node.js、PHP、Python 或 Ruby 伺服器用戶端程式庫時,請選取鎖定模式。

    第一組 Cloud Firestore 安全性規則會套用至預設規則 Cloud Firestore 資料庫如果您為專案建立多個資料庫 您可以為各個資料庫部署 Cloud Firestore 安全性規則。

  4. 選取資料庫的位置

    • 這項位置資訊設定是專案的 預設 Google Cloud Platform (GCP) 資源位置。 請注意,這個位置會用於專案中的 GCP 服務 如果是需要位置資訊設定 (具體來說是你的預設位置) Cloud Storage 值區,以及 App Engine 應用程式 否則為必要性)。

    • 如果無法選取位置,代表您的專案已經 已有預設的 GCP 資源位置這是在專案期間所設定 您在設定需要位置的其他服務時 以及環境敘述

  5. 點選「完成」

啟用 Cloud Firestore 之後,Cloud Firestore 會一併啟用 Cloud API Manager

設定開發環境

將必要的依附元件和用戶端程式庫新增至應用程式。

Web

  1. 請按照操作說明執行下列操作: 將 Firebase 新增至您的網頁應用程式
  2. 將 Firebase 和 Cloud Firestore 程式庫新增至應用程式:
    <script src="https://www.gstatic.com/firebasejs/10.12.3/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.12.3/firebase-firestore-compat.js"></script>
    另外也可以 npm 套件的形式提供 Cloud Firestore SDK。
    npm install firebase@10.12.3 --save
    
    您必須手動同時使用 Firebase 和 Cloud Firestore。
    import firebase from "firebase/compat/app";
    // Required for side-effects
    import "firebase/firestore";
    

Web

  1. 請按照操作說明執行下列操作: 將 Firebase 新增至您的網頁應用程式
  2. Cloud Firestore SDK 是以 npm 套件的形式提供。
    npm install firebase@10.12.3 --save
    
    您必須同時匯入 Firebase 和 Cloud Firestore。
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";
    
iOS+

請按照操作說明執行下列操作: 將 Firebase 新增至 Apple 應用程式

使用 Swift Package Manager 安裝及管理 Firebase 依附元件。

  1. 在 Xcode 中保持開啟應用程式專案,然後依序選擇 [檔案] >Swift 套裝行程 > 新增套件依附元件
  2. 在系統提示時,新增 Firebase Apple 平台 SDK 存放區:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. 選擇 Firestore 程式庫。
  5. 完成後,Xcode 會自動開始解析並下載 複製到背景依附元件
Android
  1. 請按照操作說明執行下列操作: 在您的 Android 應用程式中加入 Firebase
  2. 使用 Firebase Android BoM 宣告 Android 專用 Cloud Firestore 程式庫的依附元件 模組 (應用程式層級) Gradle 檔案 (通常是 app/build.gradle.ktsapp/build.gradle)。
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.1.2"))
    
        // 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:25.0.0")
    }
    

    在尋找 Kotlin 專用的程式庫模組嗎?我們先用 2023 年 10 月版本, Kotlin 和 Java 開發人員都能依賴主要的程式庫模組 (詳情請參閱 這項計畫的常見問題)。

Dart

  1. 如果您尚未設定及調整 在 Flutter 應用程式中初始化 Firebase
  2. 在 Flutter 專案的根目錄中執行下列指令: 安裝外掛程式:
    flutter pub add cloud_firestore
  3. 完成後,請重新建構 Flutter 應用程式:
    flutter run
  4. 選擇性:改善 iOS 和請在 macOS 的建構時間中加入 預先編譯的架構

    目前,適用於 iOS 的 Firestore SDK 取決於程式碼 到 5 分鐘以上縮短建構時間 大部分情況下,只要將這行程式碼新增至 Podfile 中的 target 'Runner' do 區塊:

    target 'Runner' do
      use_frameworks!
      use_modular_headers!
    
      pod 'FirebaseFirestore',
        :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git',
        :tag => 'IOS_SDK_VERSION'
    
      flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
      target 'RunnerTests' do
        inherit! :search_paths
      end
    end

    IOS_SDK_VERSION 替換為 Firebase iOS 版本 firebase_corefirebase_sdk_version.rb 檔案。如果您不是使用最新版本的 firebase_core,請在本機 Pub 套件中尋找這個檔案 快取 (通常是 ~/.pub-cache)。

    此外,請確認您已將 CocoaPods 升級至 1.9.1 或 較高:

    gem install cocoapods

    詳情請參閱 問題 。

Java
  1. 將 Firebase Admin SDK 新增至應用程式:
    • 使用 Gradle:
      compile 'com.google.firebase:firebase-admin:1.32.0'
      
    • 使用 Maven:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>1.32.0</version>
      </dependency>
           
  2. 請按照以下操作說明初始化 Cloud Firestore 連線至環境中的適當憑證
Python
  1. 在 Python 應用程式中加入 Firebase Admin SDK:
    pip install --upgrade firebase-admin
  2. 請按照以下操作說明初始化 Cloud Firestore 連線至環境中的適當憑證
C++
  1. 請按照操作說明執行下列操作: 將 Firebase 新增至您的 C++ 專案
  2. Android 適用的 C++ 介面。
    • Gradle 依附元件。將以下內容新增至模組 (應用程式層級) Gradle 檔案 (通常是 app/build.gradle):
              android.defaultConfig.externalNativeBuild.cmake {
                arguments "-DFIREBASE_CPP_SDK_DIR=$gradle.firebase_cpp_sdk_dir"
              }
      
              apply from: "$gradle.firebase_cpp_sdk_dir/Android/firebase_dependencies.gradle"
              firebaseCpp.dependencies {
                // earlier entries
                auth
                firestore
              }
              
    • 二進位檔依附元件。同樣地,如果您要取得 二進位檔依附元件就是將以下內容新增至 CMakeLists.txt 檔案:
              add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL)
              set(firebase_libs firebase_auth firebase_firestore firebase_app)
              # Replace the target name below with the actual name of your target,
              # for example, "native-lib".
              target_link_libraries(${YOUR_TARGET_NAME_HERE} "${firebase_libs}")
              
  3. 如要設定電腦整合,請參閱「將 Firebase 新增至 C++ 專案」一文。
Unity
  1. 請按照操作說明執行下列操作: 將 Firebase 新增至您的 Unity 中 專案
  2. 使用 Unity 介面設定專案,壓縮 Android 版本。
  3. 您必須壓縮版本,以避免顯示「Error while merging dex archives」訊息。

    • 這個選項位於「Player Settings」>「Player Settings」>Android >發布中 「設定」應用程式 >縮小
    • 選項可能因 Unity 版本而異,請參閱 官方 Unity 說明文件Firebase Unity 建構偵錯指南
    • 啟用壓縮功能後,參照的方法數量仍會 超過限制,您也可以選擇在以下位置啟用 multidex
      • 如果已啟用「Player Settings」下的「Custom Gradle Template」就會mainTemplate.gradle
      • 或模組層級的 build.gradle 檔案 (如果您使用 Android Studio 建構匯出的專案)。
Node.js
  1. 將 Firebase Admin SDK 新增至應用程式:
    npm install firebase-admin --save
  2. 請按照以下操作說明初始化 Cloud Firestore 連線至環境中的適當憑證
Go
  1. 在 Go 應用程式中加入 Firebase Admin SDK:
    go get firebase.google.com/go
    
  2. 請按照以下操作說明初始化 Cloud Firestore 連線至環境中的適當憑證
PHP
  1. Cloud Firestore 伺服器用戶端程式庫 (Java、Node.js、Python、Go、PHP、C# 和 Ruby) 會使用 Google 應用程式預設憑證 進行驗證。
    • 如要從開發環境進行驗證,請設定 GOOGLE_APPLICATION_CREDENTIALS 環境變數,指向 JSON 服務帳戶金鑰檔案。您可以建立金鑰檔案 API 控制台「憑證」頁面
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • 在實際工作環境中,如果您執行應用程式,不需要進行驗證 在 App Engine 或 Compute Engine 上執行,使用與 Cloud Firestore 相同的專案。否則 設定服務帳戶
  2. 安裝並啟用 gRPC 擴充功能 ,您需要使用用戶端程式庫。
  3. 將 Cloud Firestore PHP 程式庫新增至應用程式:
    composer require google/cloud-firestore
C#
  1. Cloud Firestore 伺服器用戶端程式庫 (Java、Node.js、Python、Go、PHP、C# 和 Ruby) 會使用 Google 應用程式預設憑證 進行驗證。
    • 如要從開發環境進行驗證,請設定 GOOGLE_APPLICATION_CREDENTIALS 環境變數,指向 JSON 服務帳戶金鑰檔案。您可以建立金鑰檔案 API 控制台「憑證」頁面
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • 在實際工作環境中,如果您執行應用程式,不需要進行驗證 在 App Engine 或 Compute Engine 上執行,使用與 Cloud Firestore 相同的專案。否則 設定服務帳戶
  2. 將 Cloud Firestore C# 程式庫新增至 .csproj 檔案中的應用程式:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  3. 請將以下內容新增到 Program.cs 檔案中:
    using Google.Cloud.Firestore;
Ruby
  1. Cloud Firestore 伺服器用戶端程式庫 (Java、Node.js、Python、Go、PHP、C# 和 Ruby) 會使用 Google 應用程式預設憑證 進行驗證。
    • 如要從開發環境進行驗證,請設定 GOOGLE_APPLICATION_CREDENTIALS 環境變數,指向 JSON 服務帳戶金鑰檔案。您可以建立金鑰檔案 API 控制台「憑證」頁面
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • 在實際工作環境中,如果您執行應用程式,不需要進行驗證 在 App Engine 或 Compute Engine 上執行,使用與 Cloud Firestore 相同的專案。否則 設定服務帳戶
  2. 將 Cloud Firestore Ruby 程式庫新增至 Gemfile 中的應用程式:
    gem "google-cloud-firestore"
  3. 使用以下指令,從 Gemfile 安裝依附元件:
    bundle install

(選用) 使用 Firebase 本機模擬器套件設計原型並進行測試

對行動開發人員來說,必須先介紹應用程式如何寫入與讀取 接著介紹一組工具 原型和測試 Cloud Firestore 功能: Firebase 本機模擬器套件。如想嘗試不同的資料模型 將安全性規則最佳化,或是設法找出最符合成本效益的方式 與後端互動,不必部署 對即時服務而言,也是一個好主意

Cloud Firestore 模擬器屬於本機模擬器套件的一部分, 可讓應用程式與模擬的資料庫內容和設定互動,如 以及選用的模擬專案資源 (函式、其他資料庫 和安全性規則)。

使用 Cloud Firestore 模擬器只需要幾個步驟:

  1. 將一行程式碼新增至應用程式的測試設定,即可與模擬器連線。
  2. 從本機專案目錄的根目錄中執行 firebase emulators:start
  3. 使用 Cloud Firestore 平台從應用程式的原型程式碼發出呼叫 SDK。

如需詳細的有關 Cloud Firestore 和 Cloud Functions 的逐步操作說明,請參閱。建議您也參閱「本機模擬器套件簡介」一文。

初始化 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);


// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);

FIREBASE_CONFIGURATION 替換為網頁應用程式 firebaseConfig.

如要在裝置連線中斷時保留資料,請參閱啟用離線資料說明文件。

Web

import firebase from "firebase/app";
import "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
firebase.initializeApp(firebaseConfig);


// Initialize Cloud Firestore and get a reference to the service
const db = firebase.firestore();

FIREBASE_CONFIGURATION 替換為網頁應用程式 firebaseConfig.

如要在裝置連線中斷時保留資料,請參閱啟用離線資料說明文件。

快速
注意:這項產品不適用於 watchOS 和 App Clip 目標。
import FirebaseCore
import FirebaseFirestore
FirebaseApp.configure()

let db = Firestore.firestore()
Objective-C
注意:這項產品不適用於 watchOS 和 App Clip 目標。
@import FirebaseCore;
@import FirebaseFirestore;

// Use Firebase library to configure APIs
[FIRApp configure];
  
FIRFirestore *defaultFirestore = [FIRFirestore firestore];

Kotlin+KTX

// Access a Cloud Firestore instance from your Activity
val db = Firebase.firestore

Java

// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();

Dart

db = FirebaseFirestore.instance;
Java
Cloud Firestore SDK 的初始化方式會根據 您的環境。最常見的做法如下。如需完整參考資料 看 初始化 Admin SDK
  • 在 Google Cloud 中初始化
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use the application default credentials
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .setProjectId(projectId)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
    
  • 在自己的伺服器上初始化

    如要在自己的伺服器上使用 Firebase Admin SDK,請使用 服務帳戶

    前往 IAM 與管理員 >服務帳戶 也能前往 Google Cloud 控制台產生新的私密金鑰並儲存 JSON 檔案。然後使用該檔案初始化 SDK:

    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use a service account
    InputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json");
    GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
    
  • Python
    Cloud Firestore SDK 的初始化方式會根據 您的環境。最常見的做法如下。如需完整參考資料 看 初始化 Admin SDK
  • 在 Google Cloud 中初始化
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()

    現有的應用程式預設憑證也可用來初始化 SDK。

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore.client()
  • 在自己的伺服器上初始化

    如要在自己的伺服器上使用 Firebase Admin SDK,請使用 服務帳戶

    前往 IAM 與管理員 >服務帳戶 也能前往 Google Cloud 控制台產生新的私密金鑰並儲存 JSON 檔案。然後使用該檔案初始化 SDK:

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    # Use a service account.
    cred = credentials.Certificate('path/to/serviceAccount.json')
    
    app = firebase_admin.initialize_app(cred)
    
    db = firestore.client()
  • Python

    Cloud Firestore SDK 的初始化方式會根據 您的環境。最常見的做法如下。如需完整參考資料 看 初始化 Admin SDK
  • 在 Google Cloud 中初始化
    import firebase_admin
    from firebase_admin import firestore_async
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore_async.client()

    現有的應用程式預設憑證也可用來初始化 SDK。

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore_async.client()
  • 在自己的伺服器上初始化

    如要在自己的伺服器上使用 Firebase Admin SDK,請使用 服務帳戶

    前往 IAM 與管理員 >服務帳戶 也能前往 Google Cloud 控制台產生新的私密金鑰並儲存 JSON 檔案。然後使用該檔案初始化 SDK:

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use a service account.
    cred = credentials.Certificate('path/to/serviceAccount.json')
    
    app = firebase_admin.initialize_app(cred)
    
    db = firestore_async.client()
  • C++
    // Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().
    App::Create();
    Firestore* db = Firestore::GetInstance();
    Node.js
    Cloud Firestore SDK 的初始化方式會根據 您的環境。最常見的做法如下。如需完整參考資料 看 初始化 Admin SDK
    • 在 Cloud Functions 中初始化
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
    • 在 Google Cloud 中初始化
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp({
        credential: applicationDefault()
      });
      
      const db = getFirestore();
    • 在自己的伺服器上初始化

      如要在自己的伺服器 (或任何其他 Node.js 環境) 上使用 Firebase Admin SDK, 請使用服務帳戶。 前往 IAM 與管理員 >服務帳戶。產生新的私密金鑰並儲存 JSON 檔案。然後使用該檔案初始化 SDK:

      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      const serviceAccount = require('./path/to/serviceAccountKey.json');
      
      initializeApp({
        credential: cert(serviceAccount)
      });
      
      const db = getFirestore();
      
    Go
    Cloud Firestore SDK 的初始化方式會根據 您的環境。最常見的做法如下。如需完整參考資料 看 初始化 Admin SDK
  • 在 Google Cloud 中初始化
    import (
      "log"
    
      firebase "firebase.google.com/go"
      "google.golang.org/api/option"
    )
    
    // Use the application default credentials
    ctx := context.Background()
    conf := &firebase.Config{ProjectID: projectID}
    app, err := firebase.NewApp(ctx, conf)
    if err != nil {
      log.Fatalln(err)
    }
    
    client, err := app.Firestore(ctx)
    if err != nil {
      log.Fatalln(err)
    }
    defer client.Close()
    
  • 在自己的伺服器上初始化

    如要在自己的伺服器上使用 Firebase Admin SDK,請使用 服務帳戶

    前往 IAM 與管理員 >服務帳戶 也能前往 Google Cloud 控制台產生新的私密金鑰並儲存 JSON 檔案。然後使用該檔案初始化 SDK:

    import (
      "log"
    
      firebase "firebase.google.com/go"
      "google.golang.org/api/option"
    )
    
    // Use a service account
    ctx := context.Background()
    sa := option.WithCredentialsFile("path/to/serviceAccount.json")
    app, err := firebase.NewApp(ctx, nil, sa)
    if err != nil {
      log.Fatalln(err)
    }
    
    client, err := app.Firestore(ctx)
    if err != nil {
      log.Fatalln(err)
    }
    defer client.Close()
    
  • PHP

    PHP

    如要進一步瞭解如何安裝及建立 Cloud Firestore 用戶端,請參閱 Cloud Firestore 用戶端程式庫

    use Google\Cloud\Firestore\FirestoreClient;
    
    /**
     * Initialize Cloud Firestore with default project ID.
     */
    function setup_client_create(string $projectId = null)
    {
        // Create the Cloud Firestore client
        if (empty($projectId)) {
            // The `projectId` parameter is optional and represents which project the
            // client will act on behalf of. If not supplied, the client falls back to
            // the default project inferred from the environment.
            $db = new FirestoreClient();
            printf('Created Cloud Firestore client with default project ID.' . PHP_EOL);
        } else {
            $db = new FirestoreClient([
                'projectId' => $projectId,
            ]);
            printf('Created Cloud Firestore client with project ID: %s' . PHP_EOL, $projectId);
        }
    }
    Unity
    using Firebase.Firestore;
    using Firebase.Extensions;
    FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
    C#

    C#

    如要進一步瞭解如何安裝及建立 Cloud Firestore 用戶端,請參閱 Cloud Firestore 用戶端程式庫

    FirestoreDb db = FirestoreDb.Create(project);
    Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
    Ruby
    require "google/cloud/firestore"
    
    # The `project_id` parameter is optional and represents which project the
    # client will act on behalf of. If not supplied, the client falls back to the
    # default project inferred from the environment.
    firestore = Google::Cloud::Firestore.new project_id: project_id
    
    puts "Created Cloud Firestore client with given project ID."

    新增資料

    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
    注意:這項產品不適用於 watchOS 和 App Clip 目標。
    // 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)")
    }
    Objective-C
    注意:這項產品不適用於 watchOS 和 App Clip 目標。
    // Add a new document with a generated ID
    __block FIRDocumentReference *ref =
        [[self.db collectionWithPath:@"users"] addDocumentWithData:@{
          @"first": @"Ada",
          @"last": @"Lovelace",
          @"born": @1815
        } completion:^(NSError * _Nullable error) {
          if (error != nil) {
            NSLog(@"Error adding document: %@", error);
          } else {
            NSLog(@"Document added with ID: %@", ref.documentID);
          }
        }];

    Kotlin+KTX

    // 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);
                }
            });

    Dart

    // Create a new user with a first and last name
    final user = <String, dynamic>{
      "first": "Ada",
      "last": "Lovelace",
      "born": 1815
    };
    
    // Add a new document with a generated ID
    db.collection("users").add(user).then((DocumentReference doc) =>
        print('DocumentSnapshot added with ID: ${doc.id}'));
    Java
    DocumentReference docRef = db.collection("users").document("alovelace");
    // Add document data  with id "alovelace" using a hashmap
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Ada");
    data.put("last", "Lovelace");
    data.put("born", 1815);
    //asynchronously write data
    ApiFuture<WriteResult> result = docRef.set(data);
    // ...
    // result.get() blocks on response
    System.out.println("Update time : " + result.get().getUpdateTime());
    Python
    doc_ref = db.collection("users").document("alovelace")
    doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})

    Python

    doc_ref = db.collection("users").document("alovelace")
    await doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})
    C++
    // Add a new document with a generated ID
    Future<DocumentReference> user_ref =
        db->Collection("users").Add({{"first", FieldValue::String("Ada")},
                                     {"last", FieldValue::String("Lovelace")},
                                     {"born", FieldValue::Integer(1815)}});
    
    user_ref.OnCompletion([](const Future<DocumentReference>& future) {
      if (future.error() == Error::kErrorOk) {
        std::cout << "DocumentSnapshot added with ID: " << future.result()->id()
                  << std::endl;
      } else {
        std::cout << "Error adding document: " << future.error_message() << std::endl;
      }
    });
    Node.js
    const docRef = db.collection('users').doc('alovelace');
    
    await docRef.set({
      first: 'Ada',
      last: 'Lovelace',
      born: 1815
    });
    Go
    _, _, err := client.Collection("users").Add(ctx, map[string]interface{}{
    	"first": "Ada",
    	"last":  "Lovelace",
    	"born":  1815,
    })
    if err != nil {
    	log.Fatalf("Failed adding alovelace: %v", err)
    }
    PHP

    PHP

    如要進一步瞭解如何安裝及建立 Cloud Firestore 用戶端,請參閱 Cloud Firestore 用戶端程式庫

    $docRef = $db->collection('samples/php/users')->document('alovelace');
    $docRef->set([
        'first' => 'Ada',
        'last' => 'Lovelace',
        'born' => 1815
    ]);
    printf('Added data to the lovelace document in the users collection.' . PHP_EOL);
    Unity
    DocumentReference docRef = db.Collection("users").Document("alovelace");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
    	{ "First", "Ada" },
    	{ "Last", "Lovelace" },
    	{ "Born", 1815 },
    };
    docRef.SetAsync(user).ContinueWithOnMainThread(task => {
    	Debug.Log("Added data to the alovelace document in the users collection.");
    });
    C#
    DocumentReference docRef = db.Collection("users").Document("alovelace");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
        { "First", "Ada" },
        { "Last", "Lovelace" },
        { "Born", 1815 }
    };
    await docRef.SetAsync(user);
    Ruby
    doc_ref = firestore.doc "#{collection_path}/alovelace"
    
    doc_ref.set(
      {
        first: "Ada",
        last:  "Lovelace",
        born:  1815
      }
    )
    
    puts "Added data to the alovelace document in the users collection."

    現在,請將另一份文件新增至 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
    注意:這項產品不適用於 watchOS 和 App Clip 目標。
    // 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)")
    }
    Objective-C
    注意:這項產品不適用於 watchOS 和 App Clip 目標。
    // Add a second document with a generated ID.
    __block FIRDocumentReference *ref =
        [[self.db collectionWithPath:@"users"] addDocumentWithData:@{
          @"first": @"Alan",
          @"middle": @"Mathison",
          @"last": @"Turing",
          @"born": @1912
        } completion:^(NSError * _Nullable error) {
          if (error != nil) {
            NSLog(@"Error adding document: %@", error);
          } else {
            NSLog(@"Document added with ID: %@", ref.documentID);
          }
        }];

    Kotlin+KTX

    // 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);
                }
            });

    Dart

    // Create a new user with a first and last name
    final user = <String, dynamic>{
      "first": "Alan",
      "middle": "Mathison",
      "last": "Turing",
      "born": 1912
    };
    
    // Add a new document with a generated ID
    db.collection("users").add(user).then((DocumentReference doc) =>
        print('DocumentSnapshot added with ID: ${doc.id}'));
    Java
    DocumentReference docRef = db.collection("users").document("aturing");
    // Add document data with an additional field ("middle")
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Alan");
    data.put("middle", "Mathison");
    data.put("last", "Turing");
    data.put("born", 1912);
    
    ApiFuture<WriteResult> result = docRef.set(data);
    System.out.println("Update time : " + result.get().getUpdateTime());
    Python
    doc_ref = db.collection("users").document("aturing")
    doc_ref.set({"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912})

    Python

    doc_ref = db.collection("users").document("aturing")
    await doc_ref.set(
        {"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912}
    )
    C++
    db->Collection("users")
        .Add({{"first", FieldValue::String("Alan")},
              {"middle", FieldValue::String("Mathison")},
              {"last", FieldValue::String("Turing")},
              {"born", FieldValue::Integer(1912)}})
        .OnCompletion([](const Future<DocumentReference>& future) {
          if (future.error() == Error::kErrorOk) {
            std::cout << "DocumentSnapshot added with ID: "
                      << future.result()->id() << std::endl;
          } else {
            std::cout << "Error adding document: " << future.error_message()
                      << std::endl;
          }
        });
    Node.js
    const aTuringRef = db.collection('users').doc('aturing');
    
    await aTuringRef.set({
      'first': 'Alan',
      'middle': 'Mathison',
      'last': 'Turing',
      'born': 1912
    });
    Go
    _, _, err = client.Collection("users").Add(ctx, map[string]interface{}{
    	"first":  "Alan",
    	"middle": "Mathison",
    	"last":   "Turing",
    	"born":   1912,
    })
    if err != nil {
    	log.Fatalf("Failed adding aturing: %v", err)
    }
    PHP

    PHP

    如要進一步瞭解如何安裝及建立 Cloud Firestore 用戶端,請參閱 Cloud Firestore 用戶端程式庫

    $docRef = $db->collection('samples/php/users')->document('aturing');
    $docRef->set([
        'first' => 'Alan',
        'middle' => 'Mathison',
        'last' => 'Turing',
        'born' => 1912
    ]);
    printf('Added data to the aturing document in the users collection.' . PHP_EOL);
    Unity
    DocumentReference docRef = db.Collection("users").Document("aturing");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
    	{ "First", "Alan" },
    	{ "Middle", "Mathison" },
    	{ "Last", "Turing" },
    	{ "Born", 1912 }
    };
    docRef.SetAsync(user).ContinueWithOnMainThread(task => {
    	Debug.Log("Added data to the aturing document in the users collection.");
    });
    C#
    DocumentReference docRef = db.Collection("users").Document("aturing");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
        { "First", "Alan" },
        { "Middle", "Mathison" },
        { "Last", "Turing" },
        { "Born", 1912 }
    };
    await docRef.SetAsync(user);
    Ruby
    doc_ref = firestore.doc "#{collection_path}/aturing"
    
    doc_ref.set(
      {
        first:  "Alan",
        middle: "Mathison",
        last:   "Turing",
        born:   1912
      }
    )
    
    puts "Added data to the aturing document in the users collection."

    讀取資料

    運用數據 CANNOT TRANSLATE 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
    注意:這項產品不適用於 watchOS 和 App Clip 目標。
    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)")
    }
    Objective-C
    注意:這項產品不適用於 watchOS 和 App Clip 目標。
    [[self.db collectionWithPath:@"users"]
        getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot,
                                     NSError * _Nullable error) {
          if (error != nil) {
            NSLog(@"Error getting documents: %@", error);
          } else {
            for (FIRDocumentSnapshot *document in snapshot.documents) {
              NSLog(@"%@ => %@", document.documentID, document.data);
            }
          }
        }];

    Kotlin+KTX

    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());
                    }
                }
            });

    Dart

    await db.collection("users").get().then((event) {
      for (var doc in event.docs) {
        print("${doc.id} => ${doc.data()}");
      }
    });
    Java
    // asynchronously retrieve all users
    ApiFuture<QuerySnapshot> query = db.collection("users").get();
    // ...
    // query.get() blocks on response
    QuerySnapshot querySnapshot = query.get();
    List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      System.out.println("User: " + document.getId());
      System.out.println("First: " + document.getString("first"));
      if (document.contains("middle")) {
        System.out.println("Middle: " + document.getString("middle"));
      }
      System.out.println("Last: " + document.getString("last"));
      System.out.println("Born: " + document.getLong("born"));
    }
    Python
    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")

    Python

    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    async for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")
    C++
    Future<QuerySnapshot> users = db->Collection("users").Get();
    users.OnCompletion([](const Future<QuerySnapshot>& future) {
      if (future.error() == Error::kErrorOk) {
        for (const DocumentSnapshot& document : future.result()->documents()) {
          std::cout << document << std::endl;
        }
      } else {
        std::cout << "Error getting documents: " << future.error_message()
                  << std::endl;
      }
    });
    Node.js
    const snapshot = await db.collection('users').get();
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
    Go
    iter := client.Collection("users").Documents(ctx)
    for {
    	doc, err := iter.Next()
    	if err == iterator.Done {
    		break
    	}
    	if err != nil {
    		log.Fatalf("Failed to iterate: %v", err)
    	}
    	fmt.Println(doc.Data())
    }
    PHP

    PHP

    如要進一步瞭解如何安裝及建立 Cloud Firestore 用戶端,請參閱 Cloud Firestore 用戶端程式庫

    $usersRef = $db->collection('samples/php/users');
    $snapshot = $usersRef->documents();
    foreach ($snapshot as $user) {
        printf('User: %s' . PHP_EOL, $user->id());
        printf('First: %s' . PHP_EOL, $user['first']);
        if (!empty($user['middle'])) {
            printf('Middle: %s' . PHP_EOL, $user['middle']);
        }
        printf('Last: %s' . PHP_EOL, $user['last']);
        printf('Born: %d' . PHP_EOL, $user['born']);
        printf(PHP_EOL);
    }
    printf('Retrieved and printed out all documents from the users collection.' . PHP_EOL);
    Unity
    CollectionReference usersRef = db.Collection("users");
    usersRef.GetSnapshotAsync().ContinueWithOnMainThread(task =>
    {
      QuerySnapshot snapshot = task.Result;
      foreach (DocumentSnapshot document in snapshot.Documents)
      {
        Debug.Log(String.Format("User: {0}", document.Id));
        Dictionary<string, object> documentDictionary = document.ToDictionary();
        Debug.Log(String.Format("First: {0}", documentDictionary["First"]));
        if (documentDictionary.ContainsKey("Middle"))
        {
          Debug.Log(String.Format("Middle: {0}", documentDictionary["Middle"]));
        }
    
        Debug.Log(String.Format("Last: {0}", documentDictionary["Last"]));
        Debug.Log(String.Format("Born: {0}", documentDictionary["Born"]));
      }
    
      Debug.Log("Read all data from the users collection.");
    });
    C#
    CollectionReference usersRef = db.Collection("users");
    QuerySnapshot snapshot = await usersRef.GetSnapshotAsync();
    foreach (DocumentSnapshot document in snapshot.Documents)
    {
        Console.WriteLine("User: {0}", document.Id);
        Dictionary<string, object> documentDictionary = document.ToDictionary();
        Console.WriteLine("First: {0}", documentDictionary["First"]);
        if (documentDictionary.ContainsKey("Middle"))
        {
            Console.WriteLine("Middle: {0}", documentDictionary["Middle"]);
        }
        Console.WriteLine("Last: {0}", documentDictionary["Last"]);
        Console.WriteLine("Born: {0}", documentDictionary["Born"]);
        Console.WriteLine();
    }
    Ruby
    users_ref = firestore.col collection_path
    users_ref.get do |user|
      puts "#{user.document_id} data: #{user.data}."
    end

    確保資料安全

    如果您使用的是網頁、Android 或 Apple 平台 SDK,請使用 Firebase 驗證與 用來保護資料的 Cloud Firestore 安全性規則 例如 Cloud 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

    觀看教學影片

    有關開始使用 Cloud Firestore 的詳細指南 行動用戶端程式庫,請觀看以下影片教學課程:

    Web
    iOS+
    Android

    您可以在 Firebase 中找到更多影片 YouTube 頻道

    後續步驟

    透過以下主題加深您的知識: