本快速入门将向您展示如何设置 Cloud Firestore 企业版,添加数据,然后使用核心操作或流水线操作在 Firebase 控制台中查询您刚添加的数据。
Cloud Firestore 支持移动 SDK 或 Web SDK 和服务器客户端库:
Cloud Firestore 支持 Android、iOS、Web 等平台的 SDK。与 Cloud Firestore Security Rules 和 Firebase Authentication 结合使用时,移动 SDK 和 Web SDK 支持无服务器应用架构,客户端可直接连接到您的 Cloud Firestore 数据库。
Cloud Firestore 支持 Java、Node.js 和 Python 的服务器客户端库。使用这些客户端库设置特权服务器环境,以便全面访问您的数据库。如需详细了解这些库,请参阅服务器客户端库快速入门。
创建 Cloud Firestore 企业版数据库
如果您还没有 Firebase 项目,请创建一个,具体步骤是:在 Firebase 控制台中,点击添加项目,然后按照屏幕上的说明创建 Firebase 项目或将 Firebase 服务添加到现有 Google Cloud 项目。
在 Firebase 控制台中打开您的项目。在左侧面板中,展开构建,然后选择 Firestore 数据库。
点击创建数据库。
选择企业版作为数据库模式。
选择原生模式下的 Firestore 作为操作模式,该模式支持核心操作和流水线操作。
选择数据库的位置。
为您的 Cloud Firestore Security Rules选择一个初始模式:
- 测试模式
此模式适合刚开始使用移动和 Web 客户端库的用户,但会允许任何人读取和覆盖您的数据。测试完成后,请务必查看保护您的数据部分。
如需开始使用 Web、Apple 平台或 Android SDK,请选择测试模式。
- 生产模式
拒绝来自移动和 Web 客户端的所有读写操作。经过身份验证的应用服务器 (Python) 仍然可以访问您的数据库。
最初的一组 Cloud Firestore Security Rules将应用于您的默认 Cloud Firestore 数据库。如果您为项目创建多个数据库,则可以为每个数据库部署 Cloud Firestore Security Rules。
点击创建。
如果启用 Cloud Firestore 企业版,也就在 Cloud API 管理器中启用了相应 API。
设置开发环境
将所需的依赖项和客户端库添加到您的应用。
Web
- 按照相关说明将 Firebase 添加到您的 Web 应用。
-
Cloud Firestore SDK 可以作为 npm 软件包提供。
您需要导入 Firebase 和 Cloud Firestore。npm install firebase@12.8.0 --save
import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore";
iOS+
按照相关说明将 Firebase 添加到您的 Apple 应用。
使用 Swift Package Manager 安装和管理 Firebase 依赖项。
- 在 Xcode 中打开您的应用项目,依次点击 File(文件)> Swift Packages(Swift 软件包)> 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)中声明 Cloud Firestore Android 库的依赖项。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.7.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:26.0.2") }
是否想要查找 Kotlin 专用的库模块?从 2023 年 10 月发布的版本开始,Kotlin 和 Java 开发者可以依赖于主库模块(如需了解详情,请参阅关于此计划的常见问题解答)。
初始化 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); // When initializing Firestore, remember to use the name of the database you created earlier: const db = initializeFirestore(app, {}, 'your-new-enterprise-database');
将 FIREBASE_CONFIGURATION 替换为 Web 应用的 firebaseConfig。
如需在设备的网络连接中断时保留数据,请参阅启用离线数据文档。
Swift
import FirebaseCore import FirebaseFirestore FirebaseApp.configure() // When initializing Firestore, remember to use the name of the database you created earlier: let db = Firestore.firestore(database: "your-new-enterprise-database")
Kotlin
// Access a Cloud Firestore instance from your Activity // When initializing Firestore, remember to use the name of the database you created earlier: val firestore = FirebaseFirestore.getInstance("your-new-enterprise-database")
Java
// Access a Cloud Firestore instance from your Activity // When initializing Firestore, remember to use the name of the database you created earlier: FirebaseFirestore firestore = FirebaseFirestore.getInstance("your-new-enterprise-database");
使用核心操作添加数据
为了探索用于查询数据的核心操作和流水线操作,请使用核心操作向数据库添加数据。
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)") }
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); } });
现在,将另一个文档添加到 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)") }
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); } });
使用核心操作读取数据
使用 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)") }
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()); } } });
使用流水线操作读取数据
现在,您可以比较流水线查询体验与核心操作查询体验。
Web
const readDataPipeline = db.pipeline() .collection("users"); // Execute the pipeline and handle the result try { const querySnapshot = await execute(readDataPipeline); querySnapshot.results.forEach((result) => { console.log(`${result.id} => ${result.data()}`); }); } catch (error) { console.error("Error getting documents: ", error); }
Swift
do { // Initialize a Firestore Pipeline instance and specify the "users" collection as the // input stage. let snapshot = try await db.pipeline() .collection("users") .execute() // Execute the pipeline to retrieve documents. // Iterate through the documents in the pipeline results, similar to a regular query // snapshot. for result in snapshot.results { print("\(result.id ?? "no ID") => \(result.data)") } } catch { print("Error getting documents with pipeline: \(error)") }
Kotlin
val readDataPipeline = db.pipeline() .collection("users") // Execute the pipeline and handle the result readDataPipeline.execute() .addOnSuccessListener { result -> for (document in result) { println("${document.getId()} => ${document.getData()}") } } .addOnFailureListener { exception -> println("Error getting documents: $exception") }
Java
Pipeline readDataPipeline = db.pipeline() .collection("users"); readDataPipeline.execute() .addOnSuccessListener(new OnSuccessListener<Pipeline.Snapshot>() { @Override public void onSuccess(Pipeline.Snapshot snapshot) { for (PipelineResult result : snapshot.getResults()) { System.out.println(result.getId() + " => " + result.getData()); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { System.out.println("Error getting documents: " + e); } });
为移动和 Web SDK 保护数据安全
如果您使用的是 Web、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;
}
}
}
在将 Web、Android 或 iOS 应用部署到生产环境之前,请采取措施确保只有应用客户端才能访问您的 Cloud Firestore 数据。请参阅 App Check 文档。
如果您使用的是服务器 SDK 之一,请通过 Identity and Access Management (IAM) 来保护 Cloud Firestore 中的数据。
后续步骤
通过以下主题深入了解核心操作和流水线操作: