此快速入門向您展示如何設置Cloud Firestore,添加數據,然後查看剛在Firebase控制台中添加的數據。
創建Cloud Firestore數據庫
如果尚未創建Firebase項目,請執行以下操作:在Firebase控制台中,單擊Add project ,然後按照屏幕上的說明創建Firebase項目或將Firebase服務添加到現有GCP項目。
導航到Firebase控制台的“ Cloud Firestore”部分。系統將提示您選擇一個現有的Firebase項目。遵循數據庫創建工作流程。
為您的Cloud Firestore安全規則選擇一種啟動模式:
- 測試模式
適用於移動和Web客戶端庫入門,但允許任何人讀取和覆蓋您的數據。測試後,請確保查看“保護您的數據”部分。
要開始使用Web,iOS或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 。
設置您的開發環境
將所需的依賴項和客戶端庫添加到您的應用程序。
網頁
- 按照說明將Firebase添加到您的Web應用程序。
- 將Firebase和Cloud Firestore庫添加到您的應用中:
<script src="https://www.gstatic.com/firebasejs/8.2.10/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.2.10/firebase-firestore.js"></script>
Cloud Firestore SDK也作為npm軟件包提供。npm install firebase@8.2.10 --save
您需要同時手動要求Firebase和Cloud Firestore。const firebase = require("firebase"); // Required for side-effects require("firebase/firestore");
的iOS
- 按照說明將Firebase添加到您的iOS應用。
- 將Cloud Firestore Pod添加到您的
Podfile
pod 'Firebase/Firestore' # Optionally, include the Swift extensions if you're using Swift. pod 'FirebaseFirestoreSwift'
- 保存文件並運行
pod install
。
爪哇
- 按照說明將Firebase添加到您的Android應用。
- 使用Firebase Android BoM ,在模塊(應用程序級)Gradle文件(通常為
app/build.gradle
)中聲明Cloud Firestore Android庫的依賴app/build.gradle
。dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.6.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:22.1.1' }
Kotlin + KTX
- 按照說明將Firebase添加到您的Android應用。
- 使用Firebase Android BoM ,在模塊(應用程序級)Gradle文件(通常為
app/build.gradle
)中聲明Cloud Firestore Android庫的依賴app/build.gradle
。dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.6.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:22.1.1' }
爪哇
- 將Firebase Admin SDK添加到您的應用中:
- 使用Gradle:
compile 'com.google.firebase:firebase-admin:7.1.0'
- 使用Maven:
<dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>7.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主界面中的“ Android設置”下,選擇“發佈設置”
- 在“縮小”部分下,將“發布”和“調試”設置從“無”更改為“ ProGuard”
在為Android構建時,請啟用ProGuarding以避免Android DEX限制。為此,在Unity編輯器中:
Node.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 Application Default Credentials進行身份驗證。
- 要從您的開發環境進行身份驗證,請將
GOOGLE_APPLICATION_CREDENTIALS
環境變量設置為指向JSON服務帳戶密鑰文件。您可以在“ API控制台憑據”頁面上創建密鑰文件。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 Application Default Credentials進行身份驗證。
- 要從您的開發環境進行身份驗證,請將
GOOGLE_APPLICATION_CREDENTIALS
環境變量設置為指向JSON服務帳戶密鑰文件。您可以在“ API控制台憑據”頁面上創建密鑰文件。export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 在生產環境中,如果您使用與Cloud Firestore相同的項目在App Engine或Compute Engine上運行應用程序,則無需進行身份驗證。否則,請設置一個服務帳戶。
- 要從您的開發環境進行身份驗證,請將
- 將Cloud Firestore C#庫添加到您的
.csproj
文件中的應用中:<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 Application Default Credentials進行身份驗證。
- 要從您的開發環境進行身份驗證,請將
GOOGLE_APPLICATION_CREDENTIALS
環境變量設置為指向JSON服務帳戶密鑰文件。您可以在“ API控制台憑據”頁面上創建密鑰文件。export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 在生產環境中,如果您使用與Cloud Firestore相同的項目在App Engine或Compute Engine上運行應用程序,則無需進行身份驗證。否則,請設置一個服務帳戶。
- 要從您的開發環境進行身份驗證,請將
- 將Cloud Firestore Ruby庫添加到
Gemfile
的應用中:gem "google-cloud-firestore"
- 使用以下命令從
Gemfile
安裝依賴Gemfile
:bundle install
初始化Cloud Firestore
初始化Cloud Firestore實例:
網頁
// Initialize Cloud Firestore through Firebase firebase.initializeApp({ apiKey: '### FIREBASE API KEY ###', authDomain: '### FIREBASE AUTH DOMAIN ###', projectId: '### CLOUD FIRESTORE PROJECT ID ###' }); var db = firebase.firestore();`initializeApp`的值可以在您的Web應用的` firebaseConfig`中找到。要在設備斷開連接時保留數據,請參閱“啟用脫機數據”文檔。
迅速
import Firebase FirebaseApp.configure() let db = Firestore.firestore()
物鏡
@import Firebase; // Use Firebase library to configure APIs [FIRApp configure]; FIRFirestore *defaultFirestore = [FIRFirestore firestore];
爪哇
// 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
爪哇
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控制台中轉到IAM&admin>服務帳戶。生成一個新的私鑰並保存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控制台中轉到IAM&admin>服務帳戶。生成一個新的私鑰並保存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()
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 。- 初始化雲功能
const admin = require('firebase-admin'); admin.initializeApp(); const db = admin.firestore();
- 在Google Cloud Platform上初始化
const admin = require('firebase-admin'); admin.initializeApp({ credential: admin.credential.applicationDefault() }); const db = admin.firestore();
- 在您自己的服務器上初始化
要在您自己的服務器(或任何其他Node.js環境)上使用Firebase Admin SDK,請使用服務帳戶。在Cloud Platform控制台中轉到IAM&admin>服務帳戶。生成一個新的私鑰並保存JSON文件。然後使用該文件初始化SDK:
const admin = require('firebase-admin'); const serviceAccount = require('./path/to/serviceAccountKey.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }); const db = admin.firestore();
去
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控制台中轉到IAM&admin>服務帳戶。生成一個新的私鑰並保存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. * ``` * initialize(); * ``` */ function initialize() { // Create the Cloud Firestore client $db = new FirestoreClient(); printf('Created Cloud Firestore client with default project ID.' . PHP_EOL); }
統一
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);
紅寶石
require "google/cloud/firestore" firestore = Google::Cloud::Firestore.new project_id: project_id puts "Created Cloud Firestore client with given project ID."
新增資料
Cloud Firestore將數據存儲在文檔中,該文檔存儲在集合中。首次將數據添加到文檔時,Cloud Firestore會隱式創建集合和文檔。您無需顯式創建集合或文檔。
使用以下示例代碼創建一個新的集合和一個文檔。
網頁
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); });
迅速
017624dbc0物鏡
// 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); } }];
爪哇
// 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) }
爪哇
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(u'users').document(u'alovelace') doc_ref.set({ u'first': u'Ada', u'last': u'Lovelace', u'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() << '\n'; } else { std::cout << "Error adding document: " << future.error_message() << '\n'; } });
Node.js
const docRef = db.collection('users').doc('alovelace'); await docRef.set({ first: 'Ada', last: 'Lovelace', born: 1815 });
去
_, _, 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
$docRef = $db->collection('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);
紅寶石
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
集合。請注意,該文檔包含一個鍵值對(中間名),該鍵值對未出現在第一個文檔中。集合中的文檔可以包含不同的信息集。
網頁
// 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)") } }
物鏡
// 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); } }];
爪哇
// 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) }
爪哇
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(u'users').document(u'aturing') doc_ref.set({ u'first': u'Alan', u'middle': u'Mathison', u'last': u'Turing', u'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() << '\n'; } else { std::cout << "Error adding document: " << future.error_message() << '\n'; } });
Node.js
const aTuringRef = db.collection('users').doc('aturing'); await aTuringRef.set({ 'first': 'Alan', 'middle': 'Mathison', 'last': 'Turing', 'born': 1912 });
去
_, _, 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
$docRef = $db->collection('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);
紅寶石
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."
讀取數據
要快速驗證您已將數據添加到Cloud Firestore中,請使用Firebase控制台中的數據查看器。
您還可以使用“ get”方法來檢索整個集合。
網頁
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())") } } }
物鏡
[[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); } } }];
爪哇
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) }
爪哇
// 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(u'users') docs = users_ref.stream() 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 << '\n'; } } else { std::cout << "Error getting documents: " << future.error_message() << '\n'; } });
Node.js
const snapshot = await db.collection('users').get(); snapshot.forEach((doc) => { console.log(doc.id, '=>', doc.data()); });
去
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
$usersRef = $db->collection('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(); }
紅寶石
users_ref = firestore.col collection_path users_ref.get do |user| puts "#{user.document_id} data: #{user.data}." end
保護您的數據
如果您使用的是Web,Android或iOS 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;
}
}
}
如果您使用的是服務器SDK之一,請使用身份和訪問管理(IAM)來保護Cloud Firestore中的數據。
觀看視頻教程
有關Cloud Firestore移動和Web客戶端庫入門的詳細指南,請觀看以下視頻教程之一:
Web v8
的iOS
安卓
您可以在Firebase YouTube頻道中找到更多視頻。
下一步
通過以下主題加深您的知識: