В этом кратком руководстве показано, как настроить Cloud Firestore , добавить данные, а затем просмотреть только что добавленные данные в консоли Firebase.
Cloud Firestore поддерживает мобильные и веб-SDK, а также клиентские библиотеки для серверов:
Cloud Firestore supports SDKs for Android, iOS, and web and more . Combined with Cloud Firestore Security Rules and Firebase Authentication , the mobile and web SDKs support serverless app architectures where clients connect directly to your Cloud Firestore database.
Cloud Firestore supports server client libraries for C#, Go, Java, Node.js, PHP, Python, and Ruby. Use these client libraries to set up privileged server environments with full access to your database. Learn more about these libraries in the Quickstart for server client libraries .
Создайте базу данных Cloud Firestore
If you haven't already, create a Firebase project: In the Firebase console , click Add project , then follow the on-screen instructions to create a Firebase project or to add Firebase services to an existing Google Cloud project.
В левой панели перейдите в раздел «Базы данных и хранилища» > «Firestore» .
Нажмите «Создать базу данных» .
Выберите местоположение для вашей базы данных.
If you aren't able to select a location, then your project's "location for default Google Cloud resources" has already been set. Some of your project's resources (like the default Cloud Firestore instance) share a common location dependency, and their location can be set either during project creation or when setting up another service that shares this location dependency.
Выберите режим запуска Cloud Firestore Security Rules :
- Тестовый режим
Подходит для начала работы с библиотеками мобильного и веб-клиента, но позволяет любому читать и перезаписывать ваши данные. После тестирования обязательно ознакомьтесь с разделом «Защита данных» .
Для начала работы с веб-версией, платформами Apple или Android SDK выберите тестовый режим.
- Режим производства
Запрещает все операции чтения и записи с мобильных и веб-клиентов. Ваши аутентифицированные серверы приложений (C#, Go, Java, Node.js, PHP, Python или Ruby) по-прежнему смогут получать доступ к вашей базе данных.
Для начала работы с серверно-клиентской библиотекой на C#, Go, Java, Node.js, PHP, Python или Ruby выберите производственный режим.
Your initial set of Cloud Firestore Security Rules will apply to your default Cloud Firestore database. If you create multiple databases for your project, you can deploy Cloud Firestore Security Rules for each database.
Нажмите «Создать» .
При включении Cloud Firestore также активируется API в Cloud API Manager .
Настройте среду разработки.
Добавьте необходимые зависимости и клиентские библиотеки в ваше приложение.
Web
- Следуйте инструкциям, чтобы добавить Firebase в ваше веб-приложение .
- SDK Cloud Firestore доступен в виде пакета npm.
Вам потребуется импортировать как Firebase, так и Cloud Firestore .npm install firebase@12.15.0 --save
import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore";
Web
- Следуйте инструкциям, чтобы добавить Firebase в ваше веб-приложение .
- Добавьте в свое приложение библиотеки Firebase и Cloud Firestore :
SDK Cloud Firestore также доступен в виде пакета npm.<script src="https://www.gstatic.com/firebasejs/12.15.0/firebase-app-compat.js"></script> <script src="https://www.gstatic.com/firebasejs/12.15.0/firebase-firestore-compat.js"></script>
Вам потребуется вручную подключить Firebase и Cloud Firestore .npm install firebase@12.15.0 --save
import firebase from "firebase/compat/app"; // Required for side-effects import "firebase/firestore";
iOS+
Следуйте инструкциям, чтобы добавить Firebase в ваше приложение Apple .
Используйте Swift Package Manager для установки и управления зависимостями Firebase.
- В Xcode, открыв проект приложения, перейдите в меню File > Swift Packages > Add Package Dependency .
- При появлении запроса добавьте репозиторий Firebase Apple Platforms SDK:
- Выберите библиотеку Firestore.
- После завершения Xcode автоматически начнет разрешение и загрузку ваших зависимостей в фоновом режиме.
https://github.com/firebase/firebase-ios-sdk
Android
- Следуйте инструкциям, чтобы добавить Firebase в ваше Android-приложение .
- Используя Firebase Android BoM , укажите зависимость от библиотеки Cloud Firestore для Android в файле Gradle вашего модуля (уровня приложения) (обычно
app/build.gradle.ktsилиapp/build.gradle).dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.15.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.
(Альтернативный вариант) Объявление зависимостей библиотеки Firebase без использования BoM
Если вы решите не использовать 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.4.0") }
Looking for a Kotlin-specific library module? Starting with the October 2023 release , both Kotlin and Java developers can depend on the main library module (for details, see the FAQ about this initiative ).
Dart
- Если вы еще этого не сделали, настройте и инициализируйте Firebase в своем Flutter-приложении.
- Для установки плагина выполните следующую команду из корневой папки вашего Flutter-проекта:
flutter pub add cloud_firestore
- После завершения пересоберите ваше Flutter-приложение:
flutter run
- Дополнительно: Улучшите время сборки для iOS и macOS, включив предварительно скомпилированный фреймворк.
Currently, the Firestore SDK for iOS depends on code that can take upwards of 5 minutes to build in Xcode. To reduce build times significantly, you can use a pre-compiled version by adding this line to the
target 'Runner' doblock in your 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 endReplace IOS_SDK_VERSION with the version of the Firebase iOS SDK specified in
firebase_core'sfirebase_sdk_version.rbfile. If you're not using the latest version offirebase_core, look for this file in your local Pub package cache (usually~/.pub-cache).Кроме того, убедитесь, что вы обновили CocoaPods до версии 1.9.1 или выше:
gem install cocoapods
Для получения более подробной информации см. соответствующую проблему на GitHub .
C++
- Следуйте инструкциям, чтобы добавить Firebase в свой проект C++ .
- Интерфейс C++ для Android.
- Зависимости Gradle. Добавьте следующее в файл Gradle вашего модуля (уровня приложения) (обычно
app/build.gradle):android.defaultConfig.externalNativeBuild.cmake { arguments "-DFIREBASE_CPP_SDK_DIR=$gradle.firebase_cpp_sdk_dir" } apply from: "$gradle.firebase_cpp_sdk_dir/Android/firebase_dependencies.gradle" firebaseCpp.dependencies { // earlier entries auth firestore }
- Бинарные зависимости. Аналогичным образом, рекомендуемый способ получения бинарных зависимостей — добавить следующее в файл
CMakeLists.txt:add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) set(firebase_libs firebase_auth firebase_firestore firebase_app) # Replace the target name below with the actual name of your target, # for example, "native-lib". target_link_libraries(${YOUR_TARGET_NAME_HERE} "${firebase_libs}")
- Для настройки интеграции с настольными приложениями см. раздел «Добавление Firebase в ваш проект C++» .
Единство
- Следуйте инструкциям, чтобы добавить Firebase в ваш проект Unity .
- Используйте интерфейс Unity для настройки проекта с целью минимизации сборок Android.
- Эту опцию можно найти в разделе «Настройки плеера» > «Android» > «Настройки публикации» > «Минимизировать» .
- Параметры могут отличаться в разных версиях Unity, поэтому обратитесь к официальной документации Unity и руководству по отладке сборки Firebase Unity .
- Если после включения минификации количество используемых методов по-прежнему превышает лимит, можно включить
multidexв следующем коде:-
mainTemplate.gradleесли включена опция "Пользовательский шаблон Gradle" в настройках проигрывателя. - или файл
build.gradleна уровне модуля, если вы используете Android Studio для сборки экспортированного проекта.
-
Для предотвращения Error while merging dex archives необходимо минимизировать сборку.
(Необязательно) Создайте прототип и протестируйте его с помощью Firebase Local Emulator Suite
Прежде чем говорить о том, как ваше приложение записывает и читает данные в Cloud Firestore , разработчикам мобильных приложений следует ознакомиться с набором инструментов, которые можно использовать для прототипирования и тестирования функциональности Cloud Firestore : Firebase Local Emulator Suite . Если вы экспериментируете с различными моделями данных, оптимизируете правила безопасности или ищете наиболее экономичный способ взаимодействия с бэкэндом, возможность работать локально без развертывания работающих сервисов может оказаться отличной идеей.
A Cloud Firestore emulator is part of the Local Emulator Suite , which enables your app to interact with your emulated database content and config, as well as optionally your emulated project resources (functions, other databases, and security rules).
Использование эмулятора Cloud Firestore включает всего несколько шагов:
- Добавление строки кода в конфигурацию тестирования вашего приложения для подключения к эмулятору.
- В корневом каталоге вашего локального проекта выполните
firebase emulators:start. - Выполнение вызовов из прототипа кода вашего приложения с использованием SDK платформы Cloud Firestore как обычно.
Подробное пошаговое руководство по Cloud Firestore и Cloud Functions доступно. Также рекомендуем ознакомиться с вводной информацией о Local Emulator Suite .
Инициализация 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); // Initialize Cloud Firestore and get a reference to the service const db = getFirestore(app);
Замените FIREBASE_CONFIGURATION на значение firebaseConfig вашего веб-приложения.
Чтобы данные сохранялись при потере устройством соединения, см. документацию по включению автономной передачи данных .
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();
Замените FIREBASE_CONFIGURATION на значение firebaseConfig вашего веб-приложения.
Чтобы данные сохранялись при потере устройством соединения, см. документацию по включению автономной передачи данных .
Быстрый
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];
Kotlin
// Access a Cloud Firestore instance from your Activityval db = Firebase.firestore
Java
// Access a Cloud Firestore instance from your ActivityFirebaseFirestore db = FirebaseFirestore.getInstance();
Dart
db = FirebaseFirestore.instance;
C++
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance(). App::Create(); Firestore* db = Firestore::GetInstance();
Единство
using Firebase.Firestore; using Firebase.Extensions;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
Добавить данные
Cloud Firestore stores data in Documents, which are stored in Collections. Cloud Firestore creates collections and documents implicitly the first time you add data to the document. You do not need to explicitly create collections or documents.
Создайте новую коллекцию и документ, используя следующий пример кода.
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); });
Быстрый
// 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
// 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}'));
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; } });
Единство
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."); });
Now add another document to the users collection. Notice that this document includes a key-value pair (middle name) that does not appear in the first document. Documents in a collection can contain different sets of information.
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); });
Быстрый
// 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
// 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}'));
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; } });
Единство
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."); });
Прочитать данные
Воспользуйтесь средством просмотра данных в консоли 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()}`); }); });
Быстрый
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
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()}"); } });
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; } });
Единство
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."); });
Защитите свои данные
Если вы используете SDK для веб-платформ, Android или Apple, используйте Firebase Authentication и Cloud Firestore Security Rules для защиты ваших данных в Cloud Firestore .
Вот несколько базовых наборов правил, которые вы можете использовать для начала работы. Вы можете изменить свои правила безопасности в консоли Firebase на вкладке «Базы данных и хранилище» > «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;
}
}
}
Прежде чем развертывать веб-приложение, приложение для Android или iOS в рабочей среде, также примите меры для обеспечения доступа к данным Cloud Firestore только для клиентов вашего приложения. См. документацию по проверке приложений .
Если вы используете один из серверных SDK, воспользуйтесь системой управления идентификацией и доступом (IAM) для защиты ваших данных в Cloud Firestore .
Посмотрите видеоурок
Для получения подробных инструкций по началу работы с библиотеками мобильных клиентов Cloud Firestore посмотрите один из следующих видеоуроков:
Веб
iOS+
Android
Больше видеороликов вы найдете на YouTube-канале Firebase.
Следующие шаги
Углубите свои знания по следующим темам:
- Codelabs — Научитесь использовать Cloud Firestore в реальном приложении, следуя инструкциям в Codelabs для Android , iOS или веб-приложения .
- Модель данных — Узнайте больше о структуре данных в Cloud Firestore , включая иерархическую структуру данных и подколлекции.
- Добавление данных — Узнайте больше о создании и обновлении данных в Cloud Firestore .
- Получение данных — Узнайте больше о том, как получить данные.
- Выполнение простых и составных запросов — Узнайте, как выполнять простые и составные запросы.
- Сортировка и ограничение запросов. Узнайте, как упорядочивать и ограничивать данные, возвращаемые вашими запросами.
- Firebase agent skills — Learn how to enhance your AI development tools to execute tasks more effectively and to use Cloud Firestore best practices (like writing Cloud Firestore Security Rules ).