本快速入門向您展示瞭如何設置 Cloud Firestore、添加數據,然後在 Firebase 控制台中查看您剛剛添加的數據。
創建 Cloud Firestore 數據庫
如果您尚未創建 Firebase 項目:在Firebase 控制台中,點擊添加項目,然後按照屏幕上的說明創建 Firebase 項目或將 Firebase 服務添加到現有 GCP 項目。
導航到Firebase 控制台的Cloud Firestore部分。系統會提示您選擇現有的 Firebase 項目。遵循數據庫創建工作流程。
為您的 Cloud Firestore 安全規則選擇一種啟動模式:
- 測試模式
適合開始使用移動和 Web 客戶端庫,但允許任何人讀取和覆蓋您的數據。測試後,請務必查看保護您的數據部分。
要開始使用 Web、Apple 平台或 Android SDK,請選擇測試模式。
- 鎖定模式
拒絕來自移動和 Web 客戶端的所有讀取和寫入。經過身份驗證的應用程序服務器(C#、Go、Java、Node.js、PHP、Python 或 Ruby)仍然可以訪問您的數據庫。
要開始使用 C#、Go、Java、Node.js、PHP、Python 或 Ruby 服務器客戶端庫,請選擇鎖定模式。
為您的數據庫選擇一個位置。
此位置設置是您項目的默認 Google Cloud Platform (GCP) 資源位置。請注意,此位置將用於您的項目中需要位置設置的 GCP 服務,特別是您的默認Cloud Storage 存儲分區和您的App Engine應用(如果您使用 Cloud Scheduler,這是必需的)。
如果您無法選擇位置,則您的項目已經有一個默認的 GCP 資源位置。它是在項目創建期間或在設置需要位置設置的其他服務時設置的。
單擊完成。
當您啟用 Cloud Firestore 時,它還會啟用Cloud API Manager中的 API。
設置你的開發環境
將所需的依賴項和客戶端庫添加到您的應用程序。
Web version 8
- 按照說明將 Firebase 添加到您的 Web 應用。
- 將 Firebase 和 Cloud Firestore 庫添加到您的應用中:
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-firestore.js"></script>
Cloud Firestore SDK 也可作為 npm 包提供。npm install firebase@8.10.1 --save
您需要手動要求 Firebase 和 Cloud Firestore。const firebase = require("firebase"); // Required for side-effects require("firebase/firestore");
Web version 9
- 按照說明將 Firebase 添加到您的 Web 應用。
- Cloud Firestore SDK 以 npm 包的形式提供。
npm install firebase@9.8.2 --save
您需要同時導入 Firebase 和 Cloud Firestore。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
Java
- 按照說明將 Firebase 添加到您的 Android 應用。
- 使用Firebase Android BoM ,在您的模塊(應用級)Gradle 文件(通常是
app/build.gradle
)中聲明 Cloud Firestore Android 庫的依賴項。dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.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 庫。
(替代)在不使用 BoM 的情況下聲明 Firebase 庫依賴項
如果您選擇不使用 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:24.1.2' }
Kotlin+KTX
- 按照說明將 Firebase 添加到您的 Android 應用。
- 使用Firebase Android BoM ,在您的模塊(應用級)Gradle 文件(通常是
app/build.gradle
)中聲明 Cloud Firestore Android 庫的依賴項。dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.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-ktx' }
通過使用Firebase Android BoM ,您的應用將始終使用兼容版本的 Firebase Android 庫。
(替代)在不使用 BoM 的情況下聲明 Firebase 庫依賴項
如果您選擇不使用 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-ktx:24.1.2' }
Dart
- 如果您還沒有,請在 Flutter 應用中配置和初始化 Firebase 。
- 在 Flutter 項目的根目錄下,運行以下命令來安裝插件:
flutter pub add cloud_firestore
- 完成後,重建您的 Flutter 應用程序:
flutter run
爪哇
- 將 Firebase Admin SDK 添加到您的應用中:
- 使用 Gradle:
compile 'com.google.firebase:firebase-admin:8.1.0'
- 使用 Maven:
<dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>8.1.0</version> </dependency>
- 使用 Gradle:
- 按照以下說明在您的環境中使用正確的憑據初始化 Cloud Firestore。
Python
- 將 Firebase Admin SDK 添加到您的 Python 應用:
pip install --upgrade firebase-admin
- 按照以下說明在您的環境中使用正確的憑據初始化 Cloud Firestore。
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++ 項目。
統一
- 按照說明將 Firebase 添加到您的 Unity 項目。
- 適用於 Android 的 Unity 界面。
- 選擇文件 > 構建設置
- 將“平台”切換到“Android”,然後單擊“切換平台”
- 點擊“播放器設置...”
- 在 Unity 主 UI 中,在“Android 設置”下,選擇“發佈設置”
- 在“縮小”部分下,將發布和調試設置從“無”更改為“ProGuard”
為 Android 構建時,啟用 ProGuarding 以避免 Android DEX 限制。為此,在 Unity 編輯器中:
節點.js
- 將 Firebase Admin SDK 添加到您的應用中:
npm install firebase-admin --save
- 按照以下說明在您的環境中使用正確的憑據初始化 Cloud Firestore。
去
- 將 Firebase Admin SDK 添加到您的 Go 應用:
go get firebase.google.com/go
- 按照以下說明在您的環境中使用正確的憑據初始化 Cloud Firestore。
PHP
- Cloud Firestore 服務器客戶端庫(Java、Node.js、Python、Go、PHP、C# 和 Ruby)使用Google 應用程序默認憑據進行身份驗證。
- 要從您的開發環境進行身份驗證,請將
GOOGLE_APPLICATION_CREDENTIALS
環境變量設置為指向 JSON 服務帳戶密鑰文件。您可以在API Console Credentials 頁面上創建一個密鑰文件。export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 在您的生產環境中,如果您使用與 Cloud Firestore 相同的項目在 App Engine 或 Compute Engine 上運行應用程序,則無需進行身份驗證。否則,設置一個服務帳戶。
- 要從您的開發環境進行身份驗證,請將
- 安裝並啟用 PHP 的gRPC 擴展,您需要使用客戶端庫。
- 將 Cloud Firestore PHP 庫添加到您的應用中:
composer require google/cloud-firestore
C#
- Cloud Firestore 服務器客戶端庫(Java、Node.js、Python、Go、PHP、C# 和 Ruby)使用Google 應用程序默認憑據進行身份驗證。
- 要從您的開發環境進行身份驗證,請將
GOOGLE_APPLICATION_CREDENTIALS
環境變量設置為指向 JSON 服務帳戶密鑰文件。您可以在API Console Credentials 頁面上創建一個密鑰文件。export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 在您的生產環境中,如果您使用與 Cloud Firestore 相同的項目在 App Engine 或 Compute Engine 上運行應用程序,則無需進行身份驗證。否則,設置一個服務帳戶。
- 要從您的開發環境進行身份驗證,請將
- 在
.csproj
文件中將 Cloud Firestore C# 庫添加到您的應用:<ItemGroup> <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" /> </ItemGroup>
- 將以下內容添加到您的
Program.cs
文件中:using Google.Cloud.Firestore;
紅寶石
- Cloud Firestore 服務器客戶端庫(Java、Node.js、Python、Go、PHP、C# 和 Ruby)使用Google 應用程序默認憑據進行身份驗證。
- 要從您的開發環境進行身份驗證,請將
GOOGLE_APPLICATION_CREDENTIALS
環境變量設置為指向 JSON 服務帳戶密鑰文件。您可以在API Console Credentials 頁面上創建一個密鑰文件。export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 在您的生產環境中,如果您使用與 Cloud Firestore 相同的項目在 App Engine 或 Compute Engine 上運行應用程序,則無需進行身份驗證。否則,設置一個服務帳戶。
- 要從您的開發環境進行身份驗證,請將
- 將 Cloud Firestore Ruby 庫添加到
Gemfile
中的應用程序:gem "google-cloud-firestore"
- 使用以下命令從
Gemfile
安裝依賴項:bundle install
(可選)使用 Firebase 本地模擬器套件進行原型設計和測試
對於移動開發人員,在討論您的應用如何寫入和讀取 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 version 9
import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore"; // TODO: Replace the following with your app's Firebase project configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize Firebase const app = initializeApp(firebaseConfig); // Initialize Cloud Firestore and get a reference to the service const db = getFirestore(app);`initializeApp` 的值可以在您的網絡應用程序的`firebaseConfig`中找到。要在設備斷開連接時保留數據,請參閱啟用離線數據文檔。
Web version 8
import firebase from "firebase/app"; import "firebase/firestore"; // TODO: Replace the following with your app's Firebase project configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize Firebase firebase.initializeApp(firebaseConfig); // Initialize Cloud Firestore and get a reference to the service const db = firebase.firestore();`initializeApp` 的值可以在您的網絡應用程序的`firebaseConfig`中找到。要在設備斷開連接時保留數據,請參閱啟用離線數據文檔。
迅速
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];
Java
// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();
Kotlin+KTX
// Access a Cloud Firestore instance from your Activity
val db = Firebase.firestore
Dart
db = FirebaseFirestore.instance;
爪哇
Cloud Firestore SDK 會根據您的環境以不同的方式進行初始化。以下是最常用的方法。有關完整參考,請參閱初始化 Admin SDK 。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,請使用服務帳戶。
轉到 Cloud Platform Console 中的IAM 和管理員 > 服務帳號。生成新的私鑰並保存 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 。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, { 'projectId': project_id, }) db = firestore.client()上初始化
要在您自己的服務器上使用 Firebase Admin SDK,請使用服務帳戶。
轉到 Cloud Platform Console 中的IAM 和管理員 > 服務帳號。生成新的私鑰並保存 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') firebase_admin.initialize_app(cred) db = firestore.client()
Python
Cloud Firestore SDK 會根據您的環境以不同的方式進行初始化。以下是最常用的方法。有關完整參考,請參閱初始化 Admin 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, { 'projectId': project_id, }) db = firestore.AsyncClient()上初始化
要在您自己的服務器上使用 Firebase Admin SDK,請使用服務帳戶。
轉到 Cloud Platform Console 中的IAM 和管理員 > 服務帳號。生成新的私鑰並保存 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') firebase_admin.initialize_app(cred) db = firestore.AsyncClient()
C++
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance(). App::Create(); Firestore* db = Firestore::GetInstance();
節點.js
Cloud Firestore SDK 會根據您的環境以不同的方式進行初始化。以下是最常用的方法。有關完整參考,請參閱初始化 Admin SDK 。- 在 Cloud Functions 上初始化
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
initializeApp(); const db = getFirestore();
- 在谷歌云平台上初始化
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
initializeApp({ credential: applicationDefault() }); const db = getFirestore();
- 在自己的服務器上初始化
要在您自己的服務器(或任何其他 Node.js 環境)上使用 Firebase Admin SDK,請使用服務帳戶。轉到 Cloud Platform Console 中的IAM 和管理員 > 服務帳號。生成新的私鑰並保存 JSON 文件。然後使用該文件初始化SDK:
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
const serviceAccount = require('./path/to/serviceAccountKey.json'); initializeApp({ credential: cert(serviceAccount) }); const db = getFirestore();
符51
去
Cloud Firestore SDK 會根據您的環境以不同的方式進行初始化。以下是最常用的方法。有關完整參考,請參閱初始化 Admin SDK 。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,請使用服務帳戶。
轉到 Cloud Platform Console 中的IAM 和管理員 > 服務帳號。生成新的私鑰並保存 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
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); } }
統一
using Firebase.Firestore; using Firebase.Extensions;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
C#
FirestoreDb db = FirestoreDb.Create(project); Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
紅寶石
添加數據
Cloud Firestore 將數據存儲在 Documents 中,這些 Documents 存儲在 Collections 中。 Cloud Firestore 會在您首次向文檔添加數據時隱式創建集合和文檔。您不需要顯式創建集合或文檔。
使用以下示例代碼創建一個新集合和一個文檔。
Web version 9
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 version 8
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); });
迅速
// Add a new document with a generated ID var ref: DocumentReference? = nil ref = db.collection("users").addDocument(data: [ "first": "Ada", "last": "Lovelace", "born": 1815 ]) { err in if let err = err { print("Error adding document: \(err)") } else { print("Document added with ID: \(ref!.documentID)") } }
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); } }];
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); } });
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) }
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}'));
爪哇
Python
Python
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; } });
節點.js
去
PHP
$docRef = $db->collection('samples/php/users')->document('lovelace'); $docRef->set([ 'first' => 'Ada', 'last' => 'Lovelace', 'born' => 1815 ]); printf('Added data to the lovelace document in the users collection.' . PHP_EOL);
統一
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);
紅寶石
現在將另一個文檔添加到users
集合中。請注意,此文檔包含一個未出現在第一個文檔中的鍵值對(中間名)。集合中的文檔可以包含不同的信息集。
Web version 9
// 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 version 8
// 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); });
迅速
// Add a second document with a generated ID. ref = db.collection("users").addDocument(data: [ "first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912 ]) { err in if let err = err { print("Error adding document: \(err)") } else { print("Document added with ID: \(ref!.documentID)") } }
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); } }];
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); } });
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) }
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}'));
爪哇
Python
Python
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; } });
節點.js
去
PHP
$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);
統一
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);
紅寶石
讀取數據
要快速驗證您是否已將數據添加到 Cloud Firestore,請使用Firebase 控制台中的數據查看器。
您還可以使用“get”方法來檢索整個集合。
Web version 9
import { collection, getDocs } from "firebase/firestore"; const querySnapshot = await getDocs(collection(db, "users")); querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); });
Web version 8
db.collection("users").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); }); });
迅速
db.collection("users").getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") } else { for document in querySnapshot!.documents { print("\(document.documentID) => \(document.data())") } } }
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); } } }];
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()); } } });
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) }
Dart
await db.collection("users").get().then((event) { for (var doc in event.docs) { print("${doc.id} => ${doc.data()}"); } });
爪哇
Python
users_ref = db.collection(u'users') docs = users_ref.stream() for doc in docs: print(f'{doc.id} => {doc.to_dict()}')
Python
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; } });
節點.js
去
PHP
$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);
統一
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(); }
紅寶石
保護您的數據
如果您使用的是 Web、Android 或 Apple 平台 SDK,請使用Firebase 身份驗證和Cloud Firestore 安全規則來保護 Cloud Firestore 中的數據。
以下是一些可用於入門的基本規則集。您可以在控制台的規則選項卡中修改您的安全規則。
需要授權
// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
鎖定模式
// Deny read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
測試模式
// Allow read/write access to all users under any conditions
// Warning: **NEVER** use this rule set in production; it allows
// anyone to overwrite your entire database.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
在將 Web、Android 或 iOS 應用程序部署到生產環境之前,還應採取措施確保只有您的應用程序客戶端才能訪問您的 Cloud Firestore 數據。請參閱應用檢查文檔。
如果您使用其中一種服務器 SDK,請使用Identity and Access Management (IAM)來保護您在 Cloud Firestore 中的數據。
觀看視頻教程
有關開始使用 Cloud Firestore 移動客戶端庫的詳細指導,請觀看以下視頻教程之一:
網絡
iOS+
安卓
您可以在 Firebase YouTube 頻道中找到更多視頻。
下一步
通過以下主題加深您的知識:
- Codelabs — 按照適用於Android 、 iOS或Web的 codelab 學習在實際應用中使用 Cloud Firestore。
- 數據模型- 詳細了解 Cloud Firestore 中的數據結構,包括分層數據和子集合。
- 添加數據- 詳細了解如何在 Cloud Firestore 中創建和更新數據。
- 獲取數據- 了解有關如何檢索數據的更多信息。
- 執行簡單查詢和復合查詢— 了解如何運行簡單查詢和復合查詢。
- 排序和限制查詢了解如何對查詢返回的數據進行排序和限制。