Phần bắt đầu nhanh này chỉ cho 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 vào bảng điều khiển Firebase.
Tạo cơ sở dữ liệu Cloud Firestore
Nếu bạn chưa có, hãy tạo dự án Firebase: Trong bảng điều khiển Firebase , nhấp vào Thêm dự án , sau đó làm theo hướng dẫn trên màn hình để tạo dự án Firebase hoặc thêm dịch vụ Firebase vào dự án GCP hiện có.
Điều hướng đến phần Cloud Firestore của bảng điều khiển Firebase . Bạn sẽ được nhắc chọn một dự án Firebase hiện có. Thực hiện 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 Cloud Firestore của bạn:
- Chê độ kiểm tra
Tốt để bắt đầu với thư viện ứng dụng khách di động và web, nhưng cho phép bất kỳ ai đọc và ghi đè dữ liệu của bạn. Sau khi kiểm tra, hãy nhớ xem lại phần Bảo mật dữ liệu của bạn .
Để bắt đầu với web, nền tảng Apple hoặc Android SDK, hãy chọn chế độ thử nghiệm.
- Chế độ bị khóa
Tất cả đều đọc và ghi từ các ứng dụng di động và web. Các máy chủ ứng dụng đã xác thực của bạn (C #, Go, Java, Node.js, PHP, Python hoặc Ruby) vẫn có thể truy cập cơ sở dữ liệu của bạn.
Để bắt đầu với thư viện máy khách máy chủ C #, Go, Java, Node.js, PHP, Python hoặc Ruby, hãy chọn chế độ bị khóa.
Chọn một vị trí cho cơ sở dữ liệu của bạn.
Cài đặt vị trí này là vị trí tài nguyên Google Cloud Platform (GCP) mặc định cho dự án của bạn. Lưu ý rằng vị trí này sẽ được sử dụng cho các dịch vụ GCP trong dự án của bạn yêu cầu cài đặt vị trí, cụ thể là bộ lưu trữ đám mây mặc định và ứng dụng App Engine của bạn (bắt buộc nếu bạn sử dụng Cloud Scheduler).
Nếu bạn không thể chọn một vị trí, thì dự án của bạn đã có một vị trí tài nguyên GCP mặc định. Nó được thiết lập 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 thiết lập vị trí.
Nhấp vào Xong .
Khi bạn bật Cloud Firestore, nó cũng sẽ bật API trong Trình quản lý API đám mây .
Thiết lập môi trường phát triển của bạn
Thêm các phụ thuộc bắt buộc và thư viện ứng dụng khách vào ứng dụng của bạn.
Web version 8
- 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/8.10.1/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-firestore.js"></script>
SDK Cloud Firestore cũng có sẵn dưới dạng gói npm.npm install firebase@8.10.1 --save
Bạn sẽ cần yêu cầu cả Firebase và Cloud Firestore theo cách thủ công.const firebase = require("firebase"); // Required for side-effects require("firebase/firestore");
Web version 9
- Làm theo hướng dẫn để thêm Firebase vào ứng dụng Web của bạn .
- Cloud Firestore SDK có sẵn dưới dạng gói npm.
npm install firebase@9.8.4 --save
Bạn sẽ cần nhập cả Firebase và Cloud Firestore.import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore";
iOS +
Làm theo hướng dẫn để thêm Firebase vào ứng dụng Apple của bạn .
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 của Firebase.
- Trong Xcode, khi dự án ứng dụng của bạn đang mở, hãy điều hướng đến Tệp> Gói Swift> Thêm gói phụ thuộc .
- Khi được nhắc, hãy thêm kho lưu trữ SDK nền tảng Apple Firebase:
- Chọn thư viện Firestore.
- Khi hoàn tất, Xcode sẽ tự động bắt đầu giải quyết và tải xuống các phần phụ thuộc của bạn trong nền.
https://github.com/firebase/firebase-ios-sdk
Java
- Làm theo hướng dẫn để thêm Firebase vào ứng dụng Android của bạn .
- Sử dụng Firebase Android BoM , khai báo sự phụ thuộc cho thư viện Cloud Firestore Android trong tệp Gradle mô-đun (cấp ứng dụng) của bạn (thường là
app/build.gradle
).dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.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' }
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 Firebase Android.
(Thay thế) Khai báo các phụ thuộc thư viện Firebase mà không cần sử dụng BoM
Nếu bạn chọn không sử dụng Firebase BoM, bạn phải chỉ định từng phiên bản thư viện Firebase trong dòng phụ thuộc của nó.
Lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng của mình, chúng tôi thực sự khuyên bạn nên sử dụng BoM để quản lý các phiên bản thư viện, điều này đảm bảo rằng tất cả các 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:24.2.0' }
Kotlin+KTX
- Làm theo hướng dẫn để thêm Firebase vào ứng dụng Android của bạn .
- Sử dụng Firebase Android BoM , khai báo sự phụ thuộc cho thư viện Cloud Firestore Android trong tệp Gradle mô-đun (cấp ứng dụng) của bạn (thường là
app/build.gradle
).dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.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' }
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 Firebase Android.
(Thay thế) Khai báo các phụ thuộc thư viện Firebase mà không cần sử dụng BoM
Nếu bạn chọn không sử dụng Firebase BoM, bạn phải chỉ định từng phiên bản thư viện Firebase trong dòng phụ thuộc của nó.
Lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng của mình, chúng tôi thực sự khuyên bạn nên sử dụng BoM để quản lý các phiên bản thư viện, điều này đảm bảo rằng tất cả các 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-ktx:24.2.0' }
Dart
- Nếu bạn chưa có, hãy định cấu hình và khởi chạy Firebase trong ứng dụng Flutter của bạn.
- Từ thư mục gốc của dự án Flutter của bạn, hãy chạy lệnh sau để cài đặt plugin:
flutter pub add cloud_firestore
- Sau khi hoàn tất, hãy xây dựng lại ứng dụng Flutter của bạn:
flutter run
Java
- Thêm SDK quản trị Firebase vào ứng dụng của bạn:
- Sử dụng Gradle:
compile 'com.google.firebase:firebase-admin:9.0.0'
- Sử dụng Maven:
<dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>9.0.0</version> </dependency>
- Sử dụng Gradle:
- Làm theo hướng dẫn bên dưới để khởi chạy Cloud Firestore với 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ị Firebase vào ứng dụng Python của bạn:
pip install --upgrade firebase-admin
- Làm theo hướng dẫn bên dưới để khởi chạy Cloud Firestore với 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 ++ cho Android.
- Gradle phụ thuộc. Thêm phần sau vào tệp Gradle mô-đun (cấp ứng dụng) của bạn (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ụ thuộc nhị phân. Tương tự, cách được đề xuất để lấy các phụ thuộc nhị phân là thêm phần sau vào tệp
CMakeLists.txt
của bạn: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ích hợp máy tính để bàn , hãy xem Thêm Firebase vào dự án C ++ của bạn .
Đoàn kết
- Làm theo hướng dẫn để thêm Firebase vào dự án Unity của bạn .
- Giao diện Unity cho Android.
- Chọn Tệp> Cài đặt Bản dựng
- Chuyển 'Nền tảng' sang 'Android' và nhấp vào 'Chuyển nền tảng'
- Nhấp vào 'Cài đặt trình phát…'
- Trong giao diện người dùng Unity chính, trong 'Cài đặt dành cho Android', hãy chọn 'Cài đặt xuất bản'
- Trong phần 'Thu nhỏ', thay đổi cả cài đặt Phát hành và Gỡ lỗi từ 'Không có' thành 'ProGuard'
Khi xây dựng cho Android, hãy bật ProGuarding để tránh giới hạn DEX của Android. Để làm như vậy, trong trình chỉnh sửa Unity:
Node.js
- Thêm SDK quản trị Firebase vào ứng dụng của bạn:
npm install firebase-admin --save
- Làm theo hướng dẫn bên dưới để khởi chạy Cloud Firestore với thông tin đăng nhập phù hợp trong môi trường của bạn.
Đi
- Thêm SDK quản trị Firebase vào ứng dụng Go của bạn:
go get firebase.google.com/go
- Làm theo hướng dẫn bên dưới để khởi chạy Cloud Firestore với thông tin đăng nhập phù hợp trong môi trường của bạn.
PHP
- Các thư viện máy khách máy chủ Cloud Firestore (Java, Node.js, Python, Go, PHP, C # và Ruby) sử dụng Thông tin đăng nhập 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 của bạn, hãy đặt biến môi trường
GOOGLE_APPLICATION_CREDENTIALS
trỏ đến tệp khóa tài khoản dịch vụ JSON. Bạn có thể tạo một tệp khóa trên trang Thông tin đăng nhập của Bảng điều khiển API .export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- Trong môi trường sản xuất của mình, bạn không cần xác thực nếu bạn chạy ứng dụng của mình trên App Engine hoặc Compute Engine, sử dụ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 của bạn, hãy đặt biến môi trường
- Cài đặt và kích hoạt tiện ích mở rộng gRPC cho PHP, mà bạn sẽ cần để sử dụng thư viện máy khách.
- Thêm thư viện PHP Cloud Firestore vào ứng dụng của bạn:
composer require google/cloud-firestore
C#
- Các thư viện máy khách máy chủ Cloud Firestore (Java, Node.js, Python, Go, PHP, C # và Ruby) sử dụng Thông tin đăng nhập 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 của bạn, hãy đặt biến môi trường
GOOGLE_APPLICATION_CREDENTIALS
trỏ đến tệp khóa tài khoản dịch vụ JSON. Bạn có thể tạo một tệp khóa trên trang Thông tin đăng nhập của Bảng điều khiển API .export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- Trong môi trường sản xuất của mình, bạn không cần xác thực nếu bạn chạy ứng dụng của mình trên App Engine hoặc Compute Engine, sử dụ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 của bạ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
của bạn:using Google.Cloud.Firestore;
Ruby
- Các thư viện máy khách máy chủ Cloud Firestore (Java, Node.js, Python, Go, PHP, C # và Ruby) sử dụng Thông tin đăng nhập 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 của bạn, hãy đặt biến môi trường
GOOGLE_APPLICATION_CREDENTIALS
trỏ đến tệp khóa tài khoản dịch vụ JSON. Bạn có thể tạo một tệp khóa trên trang Thông tin đăng nhập của Bảng điều khiển API .export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- Trong môi trường sản xuất của mình, bạn không cần xác thực nếu bạn chạy ứng dụng của mình trên App Engine hoặc Compute Engine, sử dụ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 của bạ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ụ thuộc từ
Gemfile
của bạn bằng cách sử dụng:bundle install
(Tùy chọn) Nguyên mẫu và thử nghiệm với Firebase Local Emulator Suite
Đố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 của bạn ghi và đọc từ Cloud Firestore, hãy giới thiệu một bộ công cụ bạn có thể sử dụng để tạo mẫu và thử nghiệm chức năng Cloud Firestore: Firebase Local Emulator Suite. Nếu bạn đang thử các mô hình dữ liệu khác nhau, tối ưu hóa các quy tắc bảo mật của mình hoặc đang tìm cách tương tác với back-end hiệu quả nhất về chi phí, thì việc có thể làm việc cục bộ mà không cần triển khai các dịch vụ trực tiếp có thể là một ý tưởng tuyệt vời.
Trình giả lập Cloud Firestore là một phần của Bộ phần mềm giả lập cục bộ, cho phép ứng dụng của bạn tương tác với cấu hình và nội dung cơ sở dữ liệu được mô phỏng, cũng như tùy chọn các tài nguyên dự án được mô phỏng của bạn (chức năng, cơ sở dữ liệu khác và quy tắc bảo mật).
Sử dụng trình giả lập Cloud Firestore chỉ bao gồm một vài bước:
- Thêm một dòng mã vào cấu hình thử nghiệm của ứng dụng để kết nối với trình giả lập.
- Từ thư mục gốc của thư mục dự án cục bộ của bạn, chạy
firebase emulators:start
. - Thực hiện cuộc gọi từ mã nguyên mẫu của ứng dụng bằng SDK nền tảng Cloud Firestore như thường lệ.
Có sẵn hướng dẫn chi tiết liên quan đến Cloud Firestore và Cloud Functions . Bạn cũng nên xem phần giới thiệu Local Emulator Suite .
Khởi tạo Cloud Firestore
Khởi tạo một phiên bản của 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://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize Firebase const app = initializeApp(firebaseConfig); // Initialize Cloud Firestore and get a reference to the service const db = getFirestore(app);Có thể tìm thấy các giá trị cho `initializeApp` trong` firebaseConfig` của ứng dụng web của bạn. Để 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 .
Web version 8
import firebase from "firebase/app"; import "firebase/firestore"; // TODO: Replace the following with your app's Firebase project configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize Firebase firebase.initializeApp(firebaseConfig); // Initialize Cloud Firestore and get a reference to the service const db = firebase.firestore();Có thể tìm thấy các giá trị cho `initializeApp` trong` firebaseConfig` của ứng dụng web của bạn. Để 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 .
Nhanh
import FirebaseCore import FirebaseFirestore
FirebaseApp.configure() let db = Firestore.firestore()
Objective-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;
Java
Cloud Firestore SDK được khởi tạo theo nhiều cách khác nhau tùy 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. Để có tài liệu tham khảo đầy đủ, hãy xem Khởi tạo 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ị Firebase trên máy chủ của riêng bạn, hãy sử dụng tài khoản dịch vụ .
Đi tới IAM & quản trị> Tài khoản dịch vụ trong Bảng điều khiển nền tảng đám mây. Tạo khóa riêng tư mới và lưu tệp JSON. Sau đó, sử dụng tệp để khởi tạo 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 tạo theo nhiều cách khác nhau tùy 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. Để có tài liệu tham khảo đầy đủ, hãy xem Khởi tạo SDK quản trị .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()
Để sử dụng SDK quản trị Firebase trên máy chủ của riêng bạn, hãy sử dụng tài khoản dịch vụ .
Đi tới IAM & quản trị> Tài khoản dịch vụ trong Bảng điều khiển nền tảng đám mây. Tạo khóa riêng tư mới và lưu tệp JSON. Sau đó, sử dụng tệp để khởi tạo 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()
Python
Cloud Firestore SDK được khởi tạo theo nhiều cách khác nhau tùy 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. Để có tài liệu tham khảo đầy đủ, hãy xem Khởi tạo SDK quản trị .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.AsyncClient()
Để sử dụng SDK quản trị Firebase trên máy chủ của riêng bạn, hãy sử dụng tài khoản dịch vụ .
Đi tới IAM & quản trị> Tài khoản dịch vụ trong Bảng điều khiển nền tảng đám mây. Tạo khóa riêng tư mới và lưu tệp JSON. Sau đó, sử dụng tệp để khởi tạo 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.AsyncClient()
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 tạo theo nhiều cách khác nhau tùy 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. Để có tài liệu tham khảo đầy đủ, hãy xem Khởi tạo SDK quản trị .- Khởi tạo trên các Chức năng đám mây
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
initializeApp(); const db = getFirestore();
- Khởi tạo trên Google Cloud Platform
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
initializeApp({ credential: applicationDefault() }); const db = getFirestore();
- Khởi tạo trên máy chủ của riêng bạn
Để sử dụng SDK quản trị 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ụ . Đi tới IAM & quản trị> Tài khoản dịch vụ trong Bảng điều khiển nền tảng đám mây. Tạo khóa riêng tư mới và lưu tệp JSON. Sau đó, sử dụng tệp để khởi tạo 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();
Đi
Cloud Firestore SDK được khởi tạo theo nhiều cách khác nhau tùy 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. Để có tài liệu tham khảo đầy đủ, hãy xem Khởi tạo 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ị Firebase trên máy chủ của riêng bạn, hãy sử dụng tài khoản dịch vụ .
Đi tới IAM & quản trị> Tài khoản dịch vụ trong Bảng điều khiển nền tảng đám mây. Tạo khóa riêng tư mới và lưu tệp JSON. Sau đó, sử dụng tệp để khởi tạo 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. */ function setup_client_create(string $projectId = null) { // Create the Cloud Firestore client if (empty($projectId)) { // The `projectId` parameter is optional and represents which project the // client will act on behalf of. If not supplied, the client falls back to // the default project inferred from the environment. $db = new FirestoreClient(); printf('Created Cloud Firestore client with default project ID.' . PHP_EOL); } else { $db = new FirestoreClient([ 'projectId' => $projectId, ]); printf('Created Cloud Firestore client with project ID: %s' . PHP_EOL, $projectId); } }
Đoàn kết
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);
Ruby
Thêm dữ liệu
Cloud Firestore lưu trữ dữ liệu trong Tài liệu, được lưu trữ trong Bộ sưu tập. Cloud Firestore tạo bộ sưu tập và tài liệu một cách ngầm định vào 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à một tài liệu bằng cách sử dụng mã ví dụ sau.
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); });
Nhanh
// 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
// 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) }
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
Đi
PHP
$docRef = $db->collection('samples/php/users')->document('lovelace'); $docRef->set([ 'first' => 'Ada', 'last' => 'Lovelace', 'born' => 1815 ]); printf('Added data to the lovelace document in the users collection.' . PHP_EOL);
Đoàn kết
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);
Ruby
Bây giờ hãy thêm một tài liệu khác vào bộ sưu tập users
. Lưu ý rằng tài liệu này bao gồm một cặp khóa-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 bộ thông tin khác nhau.
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); });
Nhanh
// 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
// 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) }
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
Đi
PHP
$docRef = $db->collection('samples/php/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);
Đoàn kết
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);
Ruby
Đọc dữ liệu
Để nhanh chóng xác minh rằng bạn đã thêm dữ liệu vào Cloud Firestore, hãy sử dụng trình xem dữ liệu trong bảng điều khiển Firebase .
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.
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()}`); }); });
Nhanh
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
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) }
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(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; } });
Node.js
Đi
PHP
$usersRef = $db->collection('samples/php/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);
Đoàn kết
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(); }
Ruby
Bảo mật dữ liệu của bạn
Nếu bạn đang sử dụng SDK nền tảng Web, Android hoặc Apple, hãy sử dụng Xác thực Firebase và Quy tắc bảo mật Cloud Firestore để bảo mật dữ liệu của bạn 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 của mình trong tab Quy tắc của bảng điều khiển.
Yêu cầu xác thực
// 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;
}
}
}
Chế độ bị khóa
// Deny read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
Chê độ kiểm tra
// 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;
}
}
}
Trước khi bạn triển khai ứng dụng Web, Android hoặc iOS vào phiên bản sản xuất, hãy thực hiện các bước để đảm bảo rằng chỉ các ứ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 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 sử dụng Quản lý danh tính và truy cập (IAM) để bảo mật dữ liệu của bạn trong Cloud Firestore.
Xem video hướng dẫn
Để có hướng dẫn chi tiết về cách bắt đầu với thư viện ứng dụng khách di động Cloud Firestore, hãy xem một trong các video hướng dẫn sau:
Web
iOS +
Android
Bạn có thể tìm thêm video trong kênh YouTube của Firebase.
Bước tiếp theo
Đào sâu kiến thức của bạn với các chủ đề sau:
- Codelabs - Học cách sử dụng Cloud Firestore trong một ứng dụng thực bằng cách làm theo codelab dành cho Android , iOS hoặc Web .
- Mô hình dữ liệu - Tìm hiểu thêm về cách dữ liệu được cấu trúc trong Cloud Firestore, bao gồm 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.
- Nhận dữ liệu - Tìm hiểu thêm về cách truy xuất dữ liệu.
- Thực hiện các truy vấn đơn giản và phức hợp - Học cách chạy các truy vấn đơn giản và phức hợp.
- Đặt hàng 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 do các truy vấn của bạn trả về.