本快速入门向您展示如何设置 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.16.0 --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
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:31.2.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.4.2' }
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:31.2.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.4.2' }
Dart
- 如果您还没有,请在您的 Flutter 应用中配置和初始化 Firebase 。
- 从 Flutter 项目的根目录,运行以下命令来安装插件:
flutter pub add cloud_firestore
- 完成后,重建您的 Flutter 应用程序:
flutter run
- 可选:通过包含预编译框架来缩短 iOS 和 macOS 构建时间。
目前,适用于 iOS 的 Firestore SDK 依赖于在 Xcode 中构建可能需要 5 分钟以上的代码。要显着减少构建时间,您可以通过将此行添加到 Podfile 中的
target 'Runner' do
块来使用预编译版本:target 'Runner' do pod 'FirebaseFirestore', :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git', :tag => '8.15.0' # ... end
此外,请确保您已将 CocoaPods 升级到 1.9.1 或更高版本:
gem install cocoapods
有关详细信息,请参阅GitHub 上的问题。
爪哇
- 将 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>
- 使用 Gradle:
- 按照以下说明在您的环境中使用适当的凭据初始化 Cloud Firestore。
Python
- 将 Firebase Admin SDK 添加到您的 Python 应用:
pip install --upgrade firebase-admin
- 按照以下说明在您的环境中使用适当的凭据初始化 Cloud Firestore。
C++
- 按照说明将 Firebase 添加到您的 C++ 项目。
- Android 的 C++ 接口。
- 摇篮依赖。将以下内容添加到您的模块(应用程序级别)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 的统一界面。
- 选择文件 > 构建设置
- 将“平台”切换为“Android”,然后单击“切换平台”
- 单击“播放器设置...”
- 在 Unity 主界面的“Android 设置”下,选择“发布设置”
- 在“Minify”部分下,将 Release 和 Debug 设置从“None”更改为“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 控制台凭据页面上创建密钥文件。export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 在您的生产环境中,如果您在 App Engine 或 Compute Engine 上运行应用程序并使用与 Cloud Firestore 相同的项目,则无需进行身份验证。否则,设置一个服务帐户。
- 要从您的开发环境进行身份验证,请将
- 安装并启用 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 控制台凭据页面上创建密钥文件。export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 在您的生产环境中,如果您在 App Engine 或 Compute Engine 上运行应用程序并使用与 Cloud Firestore 相同的项目,则无需进行身份验证。否则,设置一个服务帐户。
- 要从您的开发环境进行身份验证,请将
- 在您的
.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 控制台凭据页面上创建密钥文件。export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 在您的生产环境中,如果您在 App Engine 或 Compute Engine 上运行应用程序并使用与 Cloud Firestore 相同的项目,则无需进行身份验证。否则,设置一个服务帐户。
- 要从您的开发环境进行身份验证,请将
- 将 Cloud Firestore Ruby 库添加到
Gemfile
中的应用:gem "google-cloud-firestore"
- 使用以下命令从
Gemfile
安装依赖项:bundle install
(可选)使用 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 introduction 。
初始化 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://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 version 8
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
。
要在设备失去连接时保留数据,请参阅启用离线数据文档。
迅速
import FirebaseCore import FirebaseFirestore
FirebaseApp.configure() let db = Firestore.firestore()
目标-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,请使用服务帐户。
转到 Google Cloud 控制台中的IAM & admin > Service accounts 。生成新的私钥并保存 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 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,请使用服务帐户。
转到 Google Cloud 控制台中的IAM & admin > Service accounts 。生成新的私钥并保存 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 。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,请使用服务帐户。
转到 Google Cloud 控制台中的IAM & admin > Service accounts 。生成新的私钥并保存 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();
节点.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();
- 在 Google Cloud 上初始化
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,请使用服务帐户。转到 Google Cloud 控制台中的IAM & admin > Service accounts 。生成新的私钥并保存 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();
去
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,请使用服务帐户。
转到 Google Cloud 控制台中的IAM & admin > Service accounts 。生成新的私钥并保存 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 客户端库。
统一
using Firebase.Firestore; using Firebase.Extensions;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
C#
C#
有关安装和创建 Cloud Firestore 客户端的更多信息,请参阅Cloud Firestore 客户端库。
红宝石
添加数据
Cloud Firestore 将数据存储在文档中,文档存储在集合中。 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)") } }
目标-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+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}'));
爪哇
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
PHP
有关安装和创建 Cloud Firestore 客户端的更多信息,请参阅Cloud Firestore 客户端库。
统一
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#
红宝石
现在将另一个文档添加到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)") } }
目标-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+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}'));
爪哇
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
PHP
有关安装和创建 Cloud Firestore 客户端的更多信息,请参阅Cloud Firestore 客户端库。
统一
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#
红宝石
读取数据
要快速验证您是否已将数据添加到 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())") } } }
目标-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+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()}"); } });
爪哇
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
PHP
有关安装和创建 Cloud Firestore 客户端的更多信息,请参阅Cloud Firestore 客户端库。
统一
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#
红宝石
保护您的数据
如果您使用的是 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,请使用身份和访问管理 (IAM)来保护您在 Cloud Firestore 中的数据。
观看视频教程
有关开始使用 Cloud Firestore 移动客户端库的详细指导,请观看以下视频教程之一:
网络
iOS+
安卓
您可以在 Firebase YouTube 频道中找到更多视频。
下一步
通过以下主题加深您的知识:
- Codelabs - 按照Android 、 iOS或Web的 codelab 学习如何在真实应用程序中使用 Cloud Firestore 。
- 数据模型- 详细了解 Cloud Firestore 中的数据结构,包括分层数据和子集合。
- 添加数据- 详细了解如何在 Cloud Firestore 中创建和更新数据。
- 获取数据— 详细了解如何检索数据。
- 执行简单和复合查询- 了解如何运行简单和复合查询。
- 排序和限制查询了解如何排序和限制查询返回的数据。