本快速入门介绍如何使用 Android、iOS 或 Web 客户端库设置 Firestore、添加数据以及读取数据。
创建 Firestore 数据库
如果您还没有 Firebase 项目,请创建一个:在 Firebase 控制台中,点击添加项目,然后按照屏幕上的说明创建 Firebase 项目或将 Firebase 服务添加到现有 GCP 项目。
在 Firebase 控制台的导航窗格中,选择 Firestore,然后点击 Firestore 的创建数据库。
为 Firestore 安全规则选择测试模式:
- 测试模式
- 此模式适合刚开始使用移动和 Web 客户端库的用户,但会允许任何人读取和覆盖您的数据。测试完成后,请务必查看保护您的数据部分。
选择数据库的位置。
此位置设置是您项目的默认 Google Cloud Platform (GCP) 资源位置。请注意:此位置将用于项目中需要位置设置的 GCP 服务,具体地说,包括您的默认 Cloud Storage 存储分区和 App Engine 应用(如果您使用 Cloud Scheduler,就需要该应用)。
如果您无法选择位置,表明您的项目已经具有默认 GCP 资源位置。它可能是在项目创建期间设置的,也可能是在需要位置设置的其他服务中设置的。
点击完成。
启用 Firestore 时,也会在 Cloud API 管理器中启用相应 API。
设置开发环境
将所需的依赖项和客户端库添加到您的应用。
Web
- 按照相关说明将 Firebase 添加到您的 Web 应用。
- 将 Firebase 库和 Firestore 库添加到您的应用中:
<script src="https://www.gstatic.com/firebasejs/8.2.3/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.2.3/firebase-firestore.js"></script>
Firestore SDK 也可以作为 npm 软件包提供。npm install firebase@8.2.3 --save
您需要手动通过 require() 函数同时引入 Firebase 和 Firestore。const firebase = require("firebase"); // Required for side-effects require("firebase/firestore");
iOS
- 按照相关说明将 Firebase 添加到您的 iOS 应用。
- 将 Firestore pod 添加到您的
Podfile
pod 'Firebase/Firestore' # Optionally, include the Swift extensions if you're using Swift. pod 'FirebaseFirestoreSwift'
- 保存文件并运行
pod install
。
Java
Android
- 按照相关说明将 Firebase 添加到您的 Android 应用。
- 在您的模块(应用级)Gradle 文件(通常为
app/build.gradle
)中声明 Firestore Android 库的依赖项:implementation 'com.google.firebase:firebase-firestore:22.0.1'
如果您的应用使用多个 Firebase 库,请考虑使用 Firebase Android BoM,这样可以确保您应用的 Firebase 库版本始终兼容。
Kotlin+KTX
Android
- 按照相关说明将 Firebase 添加到您的 Android 应用。
- 在您的模块(应用级)Gradle 文件(通常为
app/build.gradle
)中声明 Firestore Android 库的依赖项:implementation 'com.google.firebase:firebase-firestore-ktx:22.0.1'
如果您的应用使用多个 Firebase 库,请考虑使用 Firebase Android BoM,这样可以确保您应用的 Firebase 库版本始终兼容。
初始化 Firestore
初始化 Firestore 的实例:
Web
// Initialize Firestore through Firebase firebase.initializeApp({ apiKey: '### FIREBASE API KEY ###', authDomain: '### FIREBASE AUTH DOMAIN ###', projectId: '### CLOUD FIRESTORE PROJECT ID ###' }); var db = firebase.firestore();如需在设备失去网络连接时保留数据,请参阅启用离线数据文档。
Swift
import Firebase FirebaseApp.configure() let db = Firestore.firestore()
Objective-C
@import Firebase; // Use Firebase library to configure APIs [FIRApp configure]; FIRFirestore *defaultFirestore = [FIRFirestore firestore];
Java
Android
// Access a Firestore instance from your Activity FirebaseFirestore db = FirebaseFirestore.getInstance();
Kotlin+KTX
Android
// Access a Firestore instance from your Activity val db = Firebase.firestore
添加数据
Firestore 将数据存储在文档中,而文档存储在集合中。在您首次向文档添加数据时,Firestore 就会隐式创建集合和文档。您不需要显式创建集合或文档。
使用以下示例代码创建一个新集合和一个新文档。
Web
db.collection("users").add({ first: "Ada", last: "Lovelace", born: 1815 }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); }) .catch(function(error) { console.error("Error adding document: ", error); });
Swift
// 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
Android
// 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
Android
// 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) }
现在,将另一个文档添加到 users
集合中。请注意,此文档包含第一个文档中没有的一个键值对(中间名)。集合中的文档可以包含不同的信息集。
Web
// Add a second document with a generated ID. db.collection("users").add({ first: "Alan", middle: "Mathison", last: "Turing", born: 1912 }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); }) .catch(function(error) { console.error("Error adding document: ", error); });
Swift
// 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
Android
// 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
Android
// 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) }
读取数据
如需快速验证您已将数据添加到 Firestore,请使用 Firebase 控制台中的数据查看器。
您还可以使用 get
方法来检索整个集合。
Web
db.collection("users").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); }); });
Swift
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
Android
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
Android
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) }
保护您的数据
使用 Firebase 身份验证和 Firestore 安全规则保护 Firestore 中的数据。
下面是一些可助您入门的基本规则集。您可以在 Firebase 控制台的“规则”标签页中修改安全规则。
需要身份验证
// 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;
}
}
}
观看视频教程
如果需要开始使用 Firestore 移动和 Web 客户端库的详细指南,请观看以下视频教程之一:
Web v8
iOS
Android
您可以在 Firebase YouTube 频道中找到更多视频。
后续步骤
通过以下各主题深入了解相关知识:
- Codelab - 通过学习 Android 版、iOS 版或 Web 版 Codelab,了解如何在实际应用中使用 Firestore。
- 数据模型 - 详细了解 Firestore 中数据的结构组织形式,包括分层数据和子集合。
- 添加数据 - 详细了解如何在 Firestore 中创建和更新数据。
- 获取数据 - 详细了解如何检索数据。
- 执行简单查询和复合查询 - 了解如何运行简单查询和复合查询。
- 对查询结果进行排序和限制其数量 - 了解如何对查询返回的数据进行排序和限制其数量。