本快速入門導覽課程說明如何設定 Cloud Firestore、新增資料,然後在 Firebase 控制台中查看剛才新增的資料。
Cloud Firestore 支援行動或網頁 SDK 和伺服器用戶端程式庫:
Cloud Firestore 支援 Android、iOS 和網頁等平台的 SDK。搭配 Cloud Firestore Security Rules 和 Firebase Authentication,行動和網頁 SDK 支援無伺服器應用程式架構,讓用戶端直接連線至 Cloud Firestore 資料庫。
Cloud Firestore 支援 C#、Go、Java、Node.js、PHP、Python 和 Ruby 的伺服器用戶端程式庫。使用這些用戶端程式庫設定具備完整資料庫存取權的伺服器環境。如要進一步瞭解這些程式庫,請參閱伺服器用戶端程式庫快速入門導覽課程。
建立 Cloud Firestore 資料庫
如果尚未建立 Firebase 專案,請在 Firebase 控制台中按一下「新增專案」,然後按照畫面上的指示建立 Firebase 專案,或將 Firebase 服務新增至現有的 Google Cloud 專案。
按一下 [Create database] (建立資料庫)。
選取資料庫的位置。
如果無法選取位置,表示專案的「預設 Google Cloud 資源位置」已設定完畢。專案的部分資源 (例如預設 Cloud Firestore 執行個體) 具有共同的位置依附元件,您可以在建立專案時或設定其他具有此位置依附元件的服務時,設定這些資源的位置。
選取 Cloud Firestore Security Rules 的起始模式:
- 測試模式
如要開始使用網頁、Apple 平台或 Android SDK,請選取測試模式。
- 正式版模式
拒絕行動和網路用戶端的所有讀寫要求。 通過驗證的應用程式伺服器 (C#、Go、Java、Node.js、PHP、Python 或 Ruby) 仍可存取資料庫。
如要開始使用 C#、Go、Java、Node.js、PHP、Python 或 Ruby 伺服器用戶端程式庫,請選取「正式版模式」。
初始設定的 Cloud Firestore Security Rules 會套用至預設Cloud Firestore資料庫。如果為專案建立多個資料庫,可以為每個資料庫部署 Cloud Firestore Security Rules。
點選「建立」。
啟用 Cloud Firestore 時,系統也會在 Cloud API 管理工具中啟用 API。
設定開發環境
將必要的依附元件和用戶端程式庫新增至應用程式。
Web
- 按照操作說明將 Firebase 新增至您的網頁應用程式。
-
Cloud Firestore SDK 以 npm 套件的形式提供。
您需要匯入 Firebase 和 Cloud Firestore。npm install firebase@12.8.0 --save
import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore";
Web
- 按照操作說明將 Firebase 新增至您的網頁應用程式。
- 將 Firebase 和 Cloud Firestore 程式庫新增至應用程式:
Cloud Firestore SDK 也提供 npm 套件。<script src="https://www.gstatic.com/firebasejs/12.8.0/firebase-app-compat.js"></script> <script src="https://www.gstatic.com/firebasejs/12.8.0/firebase-firestore-compat.js"></script>
您需要手動要求 Firebase 和 Cloud Firestore。npm install firebase@12.8.0 --save
import firebase from "firebase/compat/app"; // Required for side-effects import "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) 中,宣告 Android 適用的 Cloud Firestore 程式庫依附元件。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.8.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 程式庫版本。
(替代做法) 不使用 BoM 宣告 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:26.1.0") }
想尋找 Kotlin 專用的程式庫模組嗎?自 2023 年 10 月發布版本起,Kotlin 和 Java 開發人員都可以依附於主要程式庫模組 (詳情請參閱這項計畫的常見問題)。
Dart
- 如果尚未完成,請在 Flutter 應用程式中設定及初始化 Firebase。
- 在 Flutter 專案的根目錄中,執行下列指令來安裝外掛程式:
flutter pub add cloud_firestore
- 完成後,請重建 Flutter 應用程式:
flutter run
- 選用:納入預先編譯的架構,縮短 iOS 和 macOS 的建構時間。
目前,iOS 適用的 Firestore SDK 依賴的程式碼可能需要 5 分鐘以上才能在 Xcode 中建構。如要大幅縮短建構時間,請在 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_core的firebase_sdk_version.rb檔案中指定的 Firebase iOS SDK 版本。如果未使用最新版本的firebase_core,請在本地 Pub 套件快取 (通常為~/.pub-cache) 中尋找這個檔案。此外,請確認您已將 CocoaPods 升級至 1.9.1 以上版本:
gem install cocoapods
詳情請參閱 GitHub 上的問題。
C++
- 按照操作說明將 Firebase 新增至 C++ 專案。
- 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}")
- 如要設定桌面整合,請參閱「將 Firebase 新增至您的 C++ 專案」。
Unity
- 按照操作說明將 Firebase 新增至您的 Unity 專案。
- 使用 Unity 介面設定專案,縮減 Android 建構作業。
- 如要查看這個選項,請依序前往「Player Settings」>「Android」>「Publishing Settings」>「Minify」。
- 不同版本的 Unity 可能會提供不同的選項,因此請參閱官方 Unity 說明文件和 Firebase Unity 建構偵錯指南。
-
如果啟用縮減功能後,參照的方法數量仍超過限制,可以啟用
multidex:-
如果已啟用「Player Settings」下的「Custom Gradle Template」,請使用
mainTemplate.gradle -
如果您使用 Android Studio 建構匯出的專案,則為模組層級的
build.gradle檔案。
-
如果已啟用「Player Settings」下的「Custom Gradle Template」,請使用
您必須縮減建構作業,才能避免收到「Error while merging dex archives」訊息。
(選用) 使用 Firebase Local Emulator Suite 製作原型並進行測試
對於行動應用程式開發人員,在說明應用程式如何寫入及讀取 Cloud Firestore 之前,我們先介紹一組可用於原型設計和測試 Cloud Firestore 功能的工具:Firebase Local Emulator Suite。如果您正在嘗試不同的資料模型、調整安全性規則,或是尋找與後端互動時最經濟實惠的方式,那麼在不部署即時服務的情況下,於本機作業會是絕佳選擇。
Cloud Firestore模擬器是 Local Emulator Suite 的一部分,可讓應用程式與模擬的資料庫內容和設定互動,以及選擇性地與模擬的專案資源 (函式、其他資料庫和安全性規則) 互動。
使用 Cloud Firestore 模擬器只需幾個步驟:
- 在應用程式的測試設定中加入一行程式碼,即可連線至模擬器。
- 從本機專案目錄的根目錄執行
firebase emulators:start。 - 使用Cloud Firestore平台 SDK,從應用程式的原型程式碼發出呼叫。
我們提供詳細的逐步操作說明,其中包含 Cloud Firestore 和 Cloud Functions。您也應該參閱 Local Emulator Suite 簡介。
初始化 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。
如要在裝置失去連線時保留資料,請參閱「啟用離線資料」說明文件。
Swift
import FirebaseCore import FirebaseFirestore
FirebaseApp.configure() let db = Firestore.firestore()
Objective-C
@import FirebaseCore; @import FirebaseFirestore; // Use Firebase library to configure APIs [FIRApp configure];
FIRFirestore *defaultFirestore = [FIRFirestore firestore];
Kotlin
// Access a Cloud Firestore instance from your Activityval db = Firebase.firestore
Java
// Access a Cloud Firestore instance from your ActivityFirebaseFirestore db = FirebaseFirestore.getInstance();
Dart
db = FirebaseFirestore.instance;
C++
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance(). App::Create(); Firestore* db = Firestore::GetInstance();
Unity
using Firebase.Firestore; using Firebase.Extensions;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
新增資料
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)") }
Objective-C
// 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
// 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}'));
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; } });
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."); });
現在將另一份文件新增至 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)") }
Objective-C
// 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
// 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}'));
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; } });
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."); });
讀取資料
使用 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)") }
Objective-C
[[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
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()}"); } });
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; } });
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."); });
確保資料安全
如果您使用網頁、Android 或 Apple 平台 SDK,請使用 Firebase Authentication 和 Cloud Firestore Security Rules,確保 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,請使用身分與存取權管理 (IAM),確保 Cloud Firestore 中的資料安全無虞。
觀看教學影片
如需開始使用 Cloud Firestore 行動版用戶端程式庫的詳細指引,請觀看下列其中一個影片教學課程:
網頁
iOS+
Android
如要觀看更多影片,請前往 Firebase YouTube 頻道。
後續步驟
深入瞭解下列主題:
- 程式碼研究室:按照 Android、iOS 或網頁的程式碼研究室,瞭解如何在實際應用程式中使用 Cloud Firestore。
- 資料模型:進一步瞭解 Cloud Firestore 中的資料結構,包括階層式資料和子集合。
- 新增資料:進一步瞭解如何在 Cloud Firestore 中建立及更新資料。
- 取得資料:進一步瞭解如何擷取資料。
- 執行簡單和複合查詢:瞭解如何執行簡單和複合查詢。
- 排序及限制查詢:瞭解如何排序及限制查詢傳回的資料。