Hướng dẫn bắt đầu nhanh này sẽ hướng dẫn bạn cách thiết lập Cloud Firestore, thêm dữ liệu, sau đó xem dữ liệu bạn vừa thêm trong bảng điều khiển của Firebase.
Tạo cơ sở dữ liệu Cloud Firestore
Tạo một dự án Firebase (nếu bạn chưa có): Trong bảng điều khiển của Firebase, hãy nhấp vào Thêm dự án, sau đó làm theo hướng dẫn trên màn hình để tạo một dự án Firebase hoặc thêm các dịch vụ Firebase vào một dự án GCP hiện có.
Chuyển đến phần Cloud Firestore trong bảng điều khiển của Firebase. Bạn sẽ được nhắc chọn một dự án Firebase hiện có. Làm theo quy trình tạo cơ sở dữ liệu.
Chọn chế độ bắt đầu cho Quy tắc bảo mật của Cloud Firestore:
- Chế độ thử nghiệm
Phù hợp để bắt đầu sử dụng thư viện ứng dụng dành cho thiết bị di động và web, nhưng cho phép mọi người đọc và ghi đè dữ liệu của bạn. Sau khi kiểm thử, hãy nhớ xem lại phần Bảo mật dữ liệu của bạn.
Để bắt đầu sử dụng web, các nền tảng của Apple hoặc SDK Android, hãy chọn chế độ thử nghiệm.
- Chế độ khoá
Từ chối tất cả hoạt động đọc và ghi từ ứng dụng di động và web. Các máy chủ ứng dụng đã xác thực (C#, Go, Java, Node.js, PHP, Python hoặc Ruby) vẫn có thể truy cập vào cơ sở dữ liệu của bạn.
Để bắt đầu sử dụng thư viện ứng dụng máy chủ C#, Go, Java, Node.js, PHP, Python hoặc Ruby, hãy chọn chế độ khoá.
Bộ Quy tắc bảo mật của Cloud Firestore ban đầu sẽ áp dụng cho cơ sở dữ liệu mặc định của Cloud Firestore. Nếu tạo nhiều cơ sở dữ liệu cho dự án của mình, bạn có thể triển khai Quy tắc bảo mật Cloud Firestore cho từng cơ sở dữ liệu.
Chọn vị trí cho cơ sở dữ liệu.
Chế độ cài đặt vị trí này là vị trí tài nguyên Google Cloud Platform (GCP) mặc định trong dự án của bạn. Xin lưu ý rằng thông tin vị trí này sẽ được dùng cho các dịch vụ GCP trong dự án của bạn mà yêu cầu phải có chế độ cài đặt vị trí, cụ thể là bộ chứa Cloud Storage mặc định và ứng dụng App Engine của bạn (bắt buộc nếu bạn sử dụng Trình lập lịch biểu đám mây).
Nếu bạn không thể chọn một vị trí, thì nghĩa là dự án của bạn đã có vị trí tài nguyên GCP mặc định. Chính sách này được đặt trong quá trình tạo dự án hoặc khi thiết lập một dịch vụ khác yêu cầu chế độ cài đặt vị trí.
Nhấp vào Xong.
Khi bạn bật Cloud Firestore, bạn cũng sẽ bật API này trong Cloud API Manager.
Thiết lập môi trường phát triển
Thêm các phần phụ thuộc và thư viện ứng dụng bắt buộc vào ứng dụng của bạn.
API được đặt tên trong vùng chứa tên của web
- Làm theo hướng dẫn để thêm Firebase vào ứng dụng web của bạn.
- Thêm thư viện Firebase và Cloud Firestore vào ứng dụng của bạn:
<script src="https://www.gstatic.com/firebasejs/10.11.1/firebase-app-compat.js"></script> <script src="https://www.gstatic.com/firebasejs/10.11.1/firebase-firestore-compat.js"></script>
Cloud Firestore SDK cũng được cung cấp dưới dạng gói npm.npm install firebase@10.11.1 --save
Bạn sẽ cần yêu cầu cả Firebase và Cloud Firestore theo cách thủ công.import firebase from "firebase/compat/app"; // Required for side-effects import "firebase/firestore";
API mô-đun web
- Làm theo hướng dẫn để thêm Firebase vào ứng dụng web của bạn.
-
Cloud Firestore SDK được cung cấp dưới dạng gói npm.
npm install firebase@10.11.1 --save
Bạn sẽ cần nhập cả Firebase và Cloud Firestore.import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore";
iOS trở lên
Làm theo hướng dẫn để thêm Firebase vào ứng dụng Apple.
Sử dụng Trình quản lý gói Swift để cài đặt và quản lý các phần phụ thuộc Firebase.
- Trong Xcode, khi dự án ứng dụng của bạn đang mở, hãy chuyển đến File > Swift Packages > Add Package Dependency (Tệp > Gói Swift > Thêm phần phụ thuộc gói).
- Khi được nhắc, hãy thêm kho lưu trữ SDK cho các nền tảng Firebase của Apple:
- Chọn thư viện Firestore.
- Khi hoàn tất, Xcode sẽ tự động bắt đầu phân giải và tải các phần phụ thuộc xuống ở chế độ nền.
https://github.com/firebase/firebase-ios-sdk
Android
- Làm theo hướng dẫn để thêm Firebase vào ứng dụng Android.
- Sử dụng Firebase Android BoM, khai báo phần phụ thuộc cho thư viện Cloud Firestore dành cho Android trong tệp Gradle mô-đun (cấp ứng dụng) (thường là
app/build.gradle.kts
hoặcapp/build.gradle
).dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.0.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") }
Bằng cách sử dụng Firebase Android BoM, ứng dụng của bạn sẽ luôn sử dụng các phiên bản tương thích của thư viện Android trên Firebase.
(Thay thế) Khai báo các phần phụ thuộc trong thư viện Firebase mà không cần sử dụng BoM
Nếu chọn không sử dụng Bảng kê khai thành phần của Firebase, bạn phải chỉ định từng phiên bản thư viện Firebase trong dòng phần phụ thuộc.
Xin lưu ý rằng nếu sử dụng nhiều thư viện Firebase trong ứng dụng của mình, bạn nên sử dụng BoM để quản lý các phiên bản thư viện nhằm đảm bảo mọi phiên bản đều tương thích.
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:25.0.0") }
Bạn đang tìm một mô-đun thư viện dành riêng cho Kotlin? Kể từ bản phát hành tháng 10 năm 2023, cả nhà phát triển Kotlin và Java đều có thể sử dụng mô-đun thư viện chính (để biết thông tin chi tiết, hãy xem Câu hỏi thường gặp về sáng kiến này).
Dart
- Hãy định cấu hình và khởi chạy Firebase trong ứng dụng Flutter nếu bạn chưa thực hiện việc này.
- Từ thư mục gốc của dự án Flutter, hãy chạy lệnh sau để cài đặt trình bổ trợ:
flutter pub add cloud_firestore
- Sau khi hoàn tất, hãy tạo lại ứng dụng Flutter:
flutter run
- Không bắt buộc: Cải thiện thời gian tạo bản dựng trên iOS và macOS bằng cách thêm khung được biên dịch trước.
Hiện tại, SDK Firestore dành cho iOS phụ thuộc vào mã. Quá trình này có thể mất tới 5 phút để tạo trong Xcode. Để giảm đáng kể thời gian tạo bản dựng, bạn có thể sử dụng một phiên bản được biên dịch trước bằng cách thêm dòng này vào khối
target 'Runner' do
trong Podfile:target 'Runner' do use_frameworks! use_modular_headers! pod 'FirebaseFirestore', :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git', :tag => 'IOS_SDK_VERSION' flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) target 'RunnerTests' do inherit! :search_paths end end
Thay thế IOS_SDK_VERSION bằng phiên bản SDK của Firebase cho iOS được chỉ định trong tệp
firebase_sdk_version.rb
củafirebase_core
. Nếu bạn không sử dụng phiên bản mới nhất củafirebase_core
, hãy tìm tệp này trong bộ nhớ đệm cục bộ của gói Pub (thường là~/.pub-cache
).Ngoài ra, hãy đảm bảo rằng bạn đã nâng cấp CocoaPods lên 1.9.1 trở lên:
gem install cocoapods
Để biết thêm thông tin, hãy xem vấn đề này trên GitHub.
Java
- Thêm SDK quản trị của Firebase vào ứng dụng của bạn:
-
Sử dụng Gradle:
compile 'com.google.firebase:firebase-admin:1.32.0'
-
Sử dụng Maven:
<dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>1.32.0</version> </dependency>
-
Sử dụng Gradle:
- Hãy làm theo hướng dẫn bên dưới để khởi chạy Cloud Firestore bằng thông tin đăng nhập phù hợp trong môi trường của bạn.
Python
- Thêm SDK quản trị của Firebase vào ứng dụng Python:
pip install --upgrade firebase-admin
- Hãy làm theo hướng dẫn bên dưới để khởi chạy Cloud Firestore bằng thông tin đăng nhập phù hợp trong môi trường của bạn.
C++
- Làm theo hướng dẫn để thêm Firebase vào dự án C++ của bạn.
- Giao diện C++ dành cho Android.
- Các phần phụ thuộc Gradle. Thêm phần sau vào tệp Gradle
(cấp ứng dụng) của mô-đun (thường là
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 }
- Phần phụ thuộc nhị phân. Tương tự, bạn nên thêm các phần phụ thuộc nhị phân vào tệp
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}")
- Để thiết lập tính năng tích hợp với máy tính, hãy xem bài viết Thêm Firebase vào dự án C++.
Unity
- Làm theo hướng dẫn để thêm Firebase vào dự án Unity của bạn.
- Sử dụng giao diện Unity để định cấu hình dự án nhằm giảm kích thước bản dựng Android.
- Bạn có thể tìm thấy tuỳ chọn này trong phần Player Settings > Android > Publishing Settings > Minify (Cài đặt trình phát > Android > Cài đặt xuất bản > Thu nhỏ).
- Mỗi phiên bản Unity có những tuỳ chọn khác nhau. Vì vậy, hãy tham khảo tài liệu chính thức về Unity và Hướng dẫn gỡ lỗi bản dựng Unity của Firebase.
-
Nếu sau khi bật tính năng giảm kích thước, số lượng phương thức được tham chiếu vẫn vượt quá giới hạn, thì bạn có thể bật
multidex
trong:-
mainTemplate.gradle
nếu Mẫu Gradle tuỳ chỉnh trong phần Player Settings (Cài đặt trình phát) được bật -
hoặc tệp
build.gradle
cấp mô-đun, nếu bạn sử dụng Android Studio để tạo dự án đã xuất.
-
Bạn phải thu nhỏ bản dựng để tránh thông báo Error while merging dex archives
.
Node.js
-
Thêm SDK quản trị của Firebase vào ứng dụng của bạn:
npm install firebase-admin --save
- Hãy làm theo hướng dẫn bên dưới để khởi chạy Cloud Firestore bằng thông tin đăng nhập phù hợp trong môi trường của bạn.
Tiến hành
- Thêm SDK quản trị của Firebase vào ứng dụng Go:
go get firebase.google.com/go
- Hãy làm theo hướng dẫn bên dưới để khởi chạy Cloud Firestore bằng thông tin đăng nhập phù hợp trong môi trường của bạn.
PHP
-
Thư viện ứng dụng máy chủ Cloud Firestore (Java, Node.js, Python, Go, PHP, C# và Ruby) sử dụng Thông tin xác thực mặc định của ứng dụng Google để xác thực.
-
Để xác thực từ môi trường phát triển, hãy đặt biến môi trường
GOOGLE_APPLICATION_CREDENTIALS
để trỏ đến một tệp khoá tài khoản dịch vụ JSON. Bạn có thể tạo tệp khoá trên trang Thông tin xác thực của bảng điều khiển API.export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- Trong môi trường phát hành chính thức, bạn không cần xác thực nếu bạn chạy ứng dụng trên App Engine hoặc Compute Engine bằng cùng một dự án mà bạn sử dụng cho Cloud Firestore. Nếu không, hãy thiết lập một tài khoản dịch vụ.
-
Để xác thực từ môi trường phát triển, hãy đặt biến môi trường
- Cài đặt và bật tiện ích gRPC cho PHP. Bạn sẽ cần tiện ích này để sử dụng thư viện ứng dụng.
-
Thêm thư viện PHP Cloud Firestore vào ứng dụng của bạn:
composer require google/cloud-firestore
C#
-
Thư viện ứng dụng máy chủ Cloud Firestore (Java, Node.js, Python, Go, PHP, C# và Ruby) sử dụng Thông tin xác thực mặc định của ứng dụng Google để xác thực.
-
Để xác thực từ môi trường phát triển, hãy đặt biến môi trường
GOOGLE_APPLICATION_CREDENTIALS
để trỏ đến một tệp khoá tài khoản dịch vụ JSON. Bạn có thể tạo tệp khoá trên trang Thông tin xác thực của bảng điều khiển API.export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- Trong môi trường phát hành chính thức, bạn không cần xác thực nếu bạn chạy ứng dụng trên App Engine hoặc Compute Engine bằng cùng một dự án mà bạn sử dụng cho Cloud Firestore. Nếu không, hãy thiết lập một tài khoản dịch vụ.
-
Để xác thực từ môi trường phát triển, hãy đặt biến môi trường
-
Thêm thư viện Cloud Firestore C# vào ứng dụng của bạn trong tệp
.csproj
:<ItemGroup> <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" /> </ItemGroup>
-
Thêm phần sau vào tệp
Program.cs
:using Google.Cloud.Firestore;
Ruby
-
Thư viện ứng dụng máy chủ Cloud Firestore (Java, Node.js, Python, Go, PHP, C# và Ruby) sử dụng Thông tin xác thực mặc định của ứng dụng Google để xác thực.
-
Để xác thực từ môi trường phát triển, hãy đặt biến môi trường
GOOGLE_APPLICATION_CREDENTIALS
để trỏ đến một tệp khoá tài khoản dịch vụ JSON. Bạn có thể tạo tệp khoá trên trang Thông tin xác thực của bảng điều khiển API.export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- Trong môi trường phát hành chính thức, bạn không cần xác thực nếu bạn chạy ứng dụng trên App Engine hoặc Compute Engine bằng cùng một dự án mà bạn sử dụng cho Cloud Firestore. Nếu không, hãy thiết lập một tài khoản dịch vụ.
-
Để xác thực từ môi trường phát triển, hãy đặt biến môi trường
-
Thêm thư viện Cloud Firestore Ruby vào ứng dụng của bạn trong
Gemfile
:gem "google-cloud-firestore"
-
Cài đặt các phần phụ thuộc từ
Gemfile
bằng cách dùng:bundle install
(Không bắt buộc) Tạo nguyên mẫu và thử nghiệm bằng Bộ công cụ mô phỏng cục bộ của Firebase
Đối với các nhà phát triển thiết bị di động, trước khi nói về cách ứng dụng ghi vào và đọc từ Cloud Firestore, hãy giới thiệu một bộ công cụ bạn có thể dùng để tạo nguyên mẫu và kiểm thử chức năng Cloud Firestore: Bộ trình mô phỏng cục bộ Firebase. Nếu đang thử các mô hình dữ liệu khác nhau, tối ưu hoá các quy tắc bảo mật hoặc cố gắng tìm cách tiết kiệm chi phí nhất để tương tác với phần phụ trợ, thì việc có thể làm việc trên máy mà không cần triển khai dịch vụ trực tiếp là một ý tưởng hay.
Trình mô phỏng Cloud Firestore là một phần của Bộ trình mô phỏng cục bộ, cho phép ứng dụng của bạn tương tác với nội dung và cấu hình cơ sở dữ liệu được mô phỏng, cũng như các tài nguyên dự án được mô phỏng (các hàm, cơ sở dữ liệu khác và quy tắc bảo mật) nếu muốn.
Để sử dụng trình mô phỏng Cloud Firestore chỉ cần thực hiện một vài bước:
- Thêm một dòng mã vào cấu hình kiểm thử của ứng dụng để kết nối với trình mô phỏng.
- Từ gốc của thư mục dự án cục bộ, hãy chạy
firebase emulators:start
. - Thực hiện lệnh gọi từ mã nguyên mẫu của ứng dụng bằng SDK nền tảng Cloud Firestore như bình thường.
Bạn có thể xem hướng dẫn chi tiết về Cloud Firestore và Cloud Functions. Bạn cũng nên xem Giới thiệu về Bộ mô phỏng cục bộ.
Khởi động Cloud Firestore
Khởi động một thực thể của Cloud Firestore:
API mô-đun 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); // Initialize Cloud Firestore and get a reference to the service const db = getFirestore(app);
Thay thế FIREBASE_CONFIGURATION bằng firebaseConfig
của ứng dụng web.
Để duy trì dữ liệu khi thiết bị mất kết nối, hãy xem tài liệu Bật dữ liệu ngoại tuyến.
API được đặt tên trong vùng chứa tên của web
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();
Thay thế FIREBASE_CONFIGURATION bằng firebaseConfig
của ứng dụng web.
Để duy trì dữ liệu khi thiết bị mất kết nối, hãy xem tài liệu Bật dữ liệu ngoại tuyến.
Swift
import FirebaseCore import FirebaseFirestore
FirebaseApp.configure() let db = Firestore.firestore()
Mục tiêu-C
@import FirebaseCore; @import FirebaseFirestore; // Use Firebase library to configure APIs [FIRApp configure];
FIRFirestore *defaultFirestore = [FIRFirestore firestore];
Kotlin+KTX
// Access a Cloud Firestore instance from your Activity
val db = Firebase.firestore
Java
// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();
Dart
db = FirebaseFirestore.instance;
Java
Cloud Firestore SDK được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là các phương pháp phổ biến nhất. Để tham khảo đầy đủ, hãy xem bài viết Khởi chạy SDK quản trị.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();
Để sử dụng SDK quản trị của Firebase trên máy chủ của riêng bạn, hãy dùng một tài khoản dịch vụ.
Chuyển đến phần IAM và quản trị viên > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo một khoá riêng tư mới và lưu tệp JSON. Sau đó, sử dụng tệp này để khởi chạy 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 được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là các phương pháp phổ biến nhất. Để tham khảo đầy đủ, hãy xem bài viết Khởi chạy SDK quản trị.import firebase_admin from firebase_admin import firestore # Application Default credentials are automatically created. app = firebase_admin.initialize_app() db = firestore.client()
Bạn cũng có thể dùng thông tin đăng nhập mặc định hiện có của ứng dụng để khởi chạy 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()
Để sử dụng SDK quản trị của Firebase trên máy chủ của riêng bạn, hãy dùng một tài khoản dịch vụ.
Chuyển đến phần IAM và quản trị viên > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo một khoá riêng tư mới và lưu tệp JSON. Sau đó, sử dụng tệp này để khởi chạy 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 được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là các phương pháp phổ biến nhất. Để tham khảo đầy đủ, hãy xem bài viết Khởi chạy SDK quản trị.import firebase_admin from firebase_admin import firestore_async # Application Default credentials are automatically created. app = firebase_admin.initialize_app() db = firestore_async.client()
Bạn cũng có thể dùng thông tin đăng nhập mặc định hiện có của ứng dụng để khởi chạy 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()
Để sử dụng SDK quản trị của Firebase trên máy chủ của riêng bạn, hãy dùng một tài khoản dịch vụ.
Chuyển đến phần IAM và quản trị viên > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo một khoá riêng tư mới và lưu tệp JSON. Sau đó, sử dụng tệp này để khởi chạy 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();
Node.js
Cloud Firestore SDK được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là các phương pháp phổ biến nhất. Để tham khảo đầy đủ, hãy xem bài viết Khởi chạy SDK quản trị.-
Khởi chạy trên Cloud Functions
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
initializeApp(); const db = getFirestore();
-
Khởi động trên Google Cloud
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
initializeApp({ credential: applicationDefault() }); const db = getFirestore();
-
Khởi động trên máy chủ của riêng bạn
Để sử dụng SDK quản trị của Firebase trên máy chủ của riêng bạn (hoặc bất kỳ môi trường Node.js nào khác), hãy sử dụng tài khoản dịch vụ. Chuyển đến phần IAM và quản trị viên > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo một khoá riêng tư mới và lưu tệp JSON. Sau đó, sử dụng tệp này để khởi chạy SDK:
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
const serviceAccount = require('./path/to/serviceAccountKey.json'); initializeApp({ credential: cert(serviceAccount) }); const db = getFirestore();
Tiến hành
Cloud Firestore SDK được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là các phương pháp phổ biến nhất. Để tham khảo đầy đủ, hãy xem bài viết Khởi chạy SDK quản trị.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()
Để sử dụng SDK quản trị của Firebase trên máy chủ của riêng bạn, hãy dùng một tài khoản dịch vụ.
Chuyển đến phần IAM và quản trị viên > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo một khoá riêng tư mới và lưu tệp JSON. Sau đó, sử dụng tệp này để khởi chạy 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
Để biết thêm thông tin về cách cài đặt và tạo ứng dụng Cloud Firestore, hãy tham khảo Thư viện ứng dụng Cloud Firestore.
Unity
using Firebase.Firestore; using Firebase.Extensions;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
C#
C#
Để biết thêm thông tin về cách cài đặt và tạo ứng dụng Cloud Firestore, hãy tham khảo Thư viện ứng dụng Cloud Firestore.
Ruby
Thêm dữ liệu
Cloud Firestore lưu trữ dữ liệu trong phần Tài liệu và dữ liệu này được lưu trữ trong Bộ sưu tập. Cloud Firestore tạo các bộ sưu tập và tài liệu ngầm trong lần đầu tiên bạn thêm dữ liệu vào tài liệu. Bạn không cần phải tạo bộ sưu tập hoặc tài liệu một cách rõ ràng.
Tạo một bộ sưu tập mới và tài liệu bằng mã ví dụ sau đây.
API mô-đun 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); }
API được đặt tên trong vùng chứa tên của 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)") }
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); } }];
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}'));
Java
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; } });
Node.js
Tiến hành
PHP
PHP
Để biết thêm thông tin về cách cài đặt và tạo ứng dụng Cloud Firestore, hãy tham khảo Thư viện ứng dụng Cloud Firestore.
Unity
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#
Ruby
Bây giờ, hãy thêm một tài liệu khác vào bộ sưu tập users
. Xin lưu ý rằng tài liệu này chứa một cặp khoá-giá trị (tên đệm) không xuất hiện trong tài liệu đầu tiên. Các tài liệu trong một bộ sưu tập có thể chứa các nhóm thông tin khác nhau.
API mô-đun 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); }
API được đặt tên trong vùng chứa tên của 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)") }
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); } }];
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}'));
Java
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; } });
Node.js
Tiến hành
PHP
PHP
Để biết thêm thông tin về cách cài đặt và tạo ứng dụng Cloud Firestore, hãy tham khảo Thư viện ứng dụng Cloud Firestore.
Unity
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#
Ruby
Đọc dữ liệu
Sử dụng trình xem dữ liệu trong bảng điều khiển của Firebase để xác minh nhanh rằng bạn đã thêm dữ liệu vào Cloud Firestore.
Bạn cũng có thể sử dụng phương thức "get" để truy xuất toàn bộ bộ sưu tập.
API mô-đun web
import { collection, getDocs } from "firebase/firestore"; const querySnapshot = await getDocs(collection(db, "users")); querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); });
API được đặt tên trong vùng chứa tên của 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)") }
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); } } }];
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()}"); } });
Java
Python
users_ref = db.collection("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; } });
Node.js
Tiến hành
PHP
PHP
Để biết thêm thông tin về cách cài đặt và tạo ứng dụng Cloud Firestore, hãy tham khảo Thư viện ứng dụng Cloud Firestore.
Unity
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#
Ruby
Bảo mật dữ liệu của bạn
Nếu bạn đang sử dụng SDK của các nền tảng Web, Android hoặc Apple, hãy sử dụng tính năng Xác thực Firebase và Quy tắc bảo mật của Cloud Firestore để bảo mật dữ liệu trong Cloud Firestore.
Dưới đây là một số bộ quy tắc cơ bản mà bạn có thể sử dụng để bắt đầu. Bạn có thể sửa đổi các quy tắc bảo mật trong thẻ Quy tắc của bảng điều khiển.
Yêu cầu xác thực
// 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;
}
}
}
Chế độ khoá
// Deny read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
Trước khi triển khai phiên bản chính thức của ứng dụng web, ứng dụng Android hoặc iOS, bạn cũng nên thực hiện các bước để đảm bảo rằng chỉ ứng dụng khách của bạn mới có thể truy cập vào dữ liệu Cloud Firestore của bạn. Xem tài liệu về Kiểm tra ứng dụng.
Nếu bạn đang sử dụng một trong các SDK máy chủ, hãy dùng giải pháp Quản lý danh tính và quyền truy cập (IAM) để bảo mật dữ liệu của mình trong Cloud Firestore.
Xem video hướng dẫn
Để được hướng dẫn chi tiết về cách bắt đầu sử dụng thư viện ứng dụng dành cho thiết bị di động Cloud Firestore, hãy xem một trong những video hướng dẫn sau:
Web
iOS trở lên
Android
Bạn có thể tìm thêm các video khác trong kênh YouTube của Firebase.
Các bước tiếp theo
Củng cố kiến thức qua các chủ đề sau:
- Lớp học lập trình – Tìm hiểu cách sử dụng Cloud Firestore trong ứng dụng thực tế bằng cách làm theo lớp học lập trình dành cho Android, iOS hoặc Web.
- Mô hình dữ liệu – Tìm hiểu thêm về cách cấu trúc dữ liệu trong Cloud Firestore, bao gồm cả dữ liệu phân cấp và tập hợp con.
- Thêm dữ liệu — Tìm hiểu thêm về cách tạo và cập nhật dữ liệu trong Cloud Firestore.
- Lấy dữ liệu – Tìm hiểu thêm về cách truy xuất dữ liệu.
- Thực hiện truy vấn đơn giản và truy vấn phức hợp — Tìm hiểu cách chạy truy vấn đơn giản và truy vấn phức hợp.
- Sắp xếp và giới hạn truy vấn Tìm hiểu cách sắp xếp và giới hạn dữ liệu mà truy vấn của bạn trả về.