Catch up on highlights from Firebase at Google I/O 2023. Learn more

Zacznij korzystać z Cloud Firestore

Ten krótki przewodnik pokazuje, jak skonfigurować Cloud Firestore, dodać dane, a następnie wyświetlić właśnie dodane dane w konsoli Firebase.

Utwórz bazę danych Cloud Firestore

  1. Jeśli jeszcze tego nie zrobiłeś, utwórz projekt Firebase: w konsoli Firebase kliknij Dodaj projekt , a następnie postępuj zgodnie z instrukcjami wyświetlanymi na ekranie, aby utworzyć projekt Firebase lub dodać usługi Firebase do istniejącego projektu GCP.

  2. Przejdź do sekcji Cloud Firestore w konsoli Firebase . Zostaniesz poproszony o wybranie istniejącego projektu Firebase. Postępuj zgodnie z przepływem pracy tworzenia bazy danych.

  3. Wybierz tryb uruchamiania reguł bezpieczeństwa Cloud Firestore:

    Tryb testowania

    Dobre do rozpoczęcia pracy z bibliotekami klienta mobilnego i internetowego, ale umożliwia każdemu odczytywanie i zastępowanie danych. Po przetestowaniu przejrzyj sekcję Zabezpiecz swoje dane .

    Aby rozpocząć korzystanie z internetu, platform Apple lub Android SDK, wybierz tryb testowy.

    Tryb zablokowany

    Odrzuca wszystkie odczyty i zapisy z klientów mobilnych i internetowych. Twoje uwierzytelnione serwery aplikacji (C#, Go, Java, Node.js, PHP, Python lub Ruby) nadal mogą uzyskiwać dostęp do Twojej bazy danych.

    Aby rozpocząć pracę z biblioteką klienta serwera C#, Go, Java, Node.js, PHP, Python lub Ruby, wybierz tryb zablokowany.

  4. Wybierz lokalizację dla swojej bazy danych.

    • To ustawienie lokalizacji jest domyślną lokalizacją zasobu Google Cloud Platform (GCP) Twojego projektu . Pamiętaj, że ta lokalizacja będzie używana w przypadku usług GCP w Twoim projekcie, które wymagają ustawienia lokalizacji, a konkretnie domyślnego zasobnika Cloud Storage i aplikacji App Engine (która jest wymagana, jeśli korzystasz z usługi Cloud Scheduler).

    • Jeśli nie możesz wybrać lokalizacji, Twój projekt ma już domyślną lokalizację zasobów GCP. Została ustawiona podczas tworzenia projektu lub podczas konfigurowania innej usługi, która wymaga ustawienia lokalizacji.

  5. Kliknij Gotowe .

Włączenie Cloud Firestore powoduje również włączenie interfejsu API w Cloud API Manager .

Skonfiguruj swoje środowisko programistyczne

Dodaj wymagane zależności i biblioteki klienta do swojej aplikacji.

Web namespaced API

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojej aplikacji internetowej .
  2. Dodaj biblioteki Firebase i Cloud Firestore do swojej aplikacji:
    <script src="https://www.gstatic.com/firebasejs/9.22.2/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.22.2/firebase-firestore-compat.js"></script>
    Pakiet Cloud Firestore SDK jest również dostępny jako pakiet npm.
    npm install firebase@9.22.2 --save
    
    Musisz ręcznie wymagać zarówno Firebase, jak i Cloud Firestore.
    import firebase from "firebase/compat/app";
    // Required for side-effects
    import "firebase/firestore";
    

Web modular API

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojej aplikacji internetowej .
  2. Pakiet Cloud Firestore SDK jest dostępny jako pakiet npm.
    npm install firebase@9.22.2 --save
    
    Musisz zaimportować zarówno Firebase, jak i Cloud Firestore.
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";
    
iOS+

Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojej aplikacji Apple .

Użyj Menedżera pakietów Swift, aby zainstalować i zarządzać zależnościami Firebase.

  1. W Xcode, przy otwartym projekcie aplikacji, przejdź do File > Swift Packages > Add Package Dependency .
  2. Po wyświetleniu monitu dodaj repozytorium Firebase Apple platforms SDK:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. Wybierz bibliotekę Firestore.
  5. Po zakończeniu Xcode automatycznie rozpocznie rozwiązywanie i pobieranie zależności w tle.

Kotlin+KTX

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojej aplikacji na Androida .
  2. Używając Firebase Android BoM , zadeklaruj zależność biblioteki Cloud Firestore Android w swoim module (na poziomie aplikacji) pliku Gradle (zwykle app/build.gradle ).
    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.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'
    }
    

    Korzystając z Firebase Android BoM , Twoja aplikacja zawsze będzie korzystać ze zgodnych wersji bibliotek Firebase Android.

    (Alternatywnie) Zadeklaruj zależności biblioteki Firebase bez korzystania z BoM

    Jeśli zdecydujesz się nie używać BoM Firebase, musisz określić każdą wersję biblioteki Firebase w jej wierszu zależności.

    Pamiętaj, że jeśli używasz w swojej aplikacji wielu bibliotek Firebase, zdecydowanie zalecamy korzystanie z BoM do zarządzania wersjami bibliotek, co zapewnia zgodność wszystkich wersji.

    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.6.1'
    }
    

Java

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojej aplikacji na Androida .
  2. Używając Firebase Android BoM , zadeklaruj zależność biblioteki Cloud Firestore Android w swoim module (na poziomie aplikacji) pliku Gradle (zwykle app/build.gradle ).
    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.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'
    }
    

    Korzystając z Firebase Android BoM , Twoja aplikacja zawsze będzie korzystać ze zgodnych wersji bibliotek Firebase Android.

    (Alternatywnie) Zadeklaruj zależności biblioteki Firebase bez korzystania z BoM

    Jeśli zdecydujesz się nie używać BoM Firebase, musisz określić każdą wersję biblioteki Firebase w jej wierszu zależności.

    Pamiętaj, że jeśli używasz w swojej aplikacji wielu bibliotek Firebase, zdecydowanie zalecamy korzystanie z BoM do zarządzania wersjami bibliotek, co zapewnia zgodność wszystkich wersji.

    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.6.1'
    }
    

Dart

  1. Jeśli jeszcze tego nie zrobiłeś, skonfiguruj i zainicjuj Firebase w swojej aplikacji Flutter.
  2. W katalogu głównym projektu Flutter uruchom następującą komendę, aby zainstalować wtyczkę:
    flutter pub add cloud_firestore
  3. Po zakończeniu odbuduj aplikację Flutter:
    flutter run
  4. Opcjonalnie: Skróć czas kompilacji systemów iOS i macOS, dołączając wstępnie skompilowaną platformę.

    Obecnie zestaw Firestore SDK dla systemu iOS jest zależny od kodu, którego zbudowanie w Xcode może zająć ponad 5 minut. Aby znacznie skrócić czas kompilacji, możesz użyć wstępnie skompilowanej wersji, dodając tę ​​linię do target 'Runner' do w swoim Podfile:

    target 'Runner' do
      pod 'FirebaseFirestore', :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git', :tag => '8.15.0'
      # ...
    end

    Dodatkowo upewnij się, że zaktualizowałeś CocoaPods do wersji 1.9.1 lub nowszej:

    gem install cocoapods

    Aby uzyskać więcej informacji, zobacz problem w serwisie GitHub .

Jawa
  1. Dodaj pakiet Firebase Admin SDK do swojej aplikacji:
    • Używanie Gradle:
      compile 'com.google.firebase:firebase-admin:1.32.0'
      
    • Używanie Mavena:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>1.32.0</version>
      </dependency>
           
  2. Postępuj zgodnie z poniższymi instrukcjami, aby zainicjować Cloud Firestore z odpowiednimi poświadczeniami w swoim środowisku.
Pyton
  1. Dodaj pakiet Firebase Admin SDK do swojej aplikacji w języku Python:
    pip install --upgrade firebase-admin
  2. Postępuj zgodnie z poniższymi instrukcjami, aby zainicjować Cloud Firestore z odpowiednimi poświadczeniami w swoim środowisku.
C++
  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojego projektu C++ .
  2. Interfejs C++ dla Androida.
    • Gradle zależności. Dodaj następujący plik do modułu Gradle (na poziomie aplikacji) (zwykle 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
              }
              
    • Zależności binarne. Podobnie zalecanym sposobem uzyskania zależności binarnych jest dodanie następującego elementu do pliku 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}")
              
  3. Aby skonfigurować integrację z komputerem , zobacz Dodawanie Firebase do projektu C++ .
Jedność
  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojego projektu Unity .
  2. Użyj interfejsu Unity, aby skonfigurować swój projekt w celu zminimalizowania kompilacji systemu Android.
  3. Musisz zminimalizować kompilację, aby uniknąć komunikatu Error while merging dex archives .

    • Opcję można znaleźć w Ustawieniach odtwarzacza > Android > Ustawienia publikowania > Minify .
    • Opcje mogą się różnić w różnych wersjach Unity, więc zapoznaj się z oficjalną dokumentacją Unity i Firebase Unity Build Debug Guide .
    • Jeśli po włączeniu minifikacji liczba przywoływanych metod nadal przekracza limit, inną opcją jest włączenie multidex w:
      • mainTemplate.gradle , jeśli włączony jest niestandardowy szablon ocen w ustawieniach odtwarzacza
      • lub plik build.gradle na poziomie modułu, jeśli używasz Android Studio do kompilowania wyeksportowanego projektu.
Node.js
  1. Dodaj pakiet Firebase Admin SDK do swojej aplikacji:
    npm install firebase-admin --save
  2. Postępuj zgodnie z poniższymi instrukcjami, aby zainicjować Cloud Firestore z odpowiednimi poświadczeniami w swoim środowisku.
Iść
  1. Dodaj pakiet Firebase Admin SDK do swojej aplikacji Go:
    go get firebase.google.com/go
    
  2. Postępuj zgodnie z poniższymi instrukcjami, aby zainicjować Cloud Firestore z odpowiednimi poświadczeniami w swoim środowisku.
PHP
  1. Biblioteki klienta serwera Cloud Firestore (Java, Node.js, Python, Go, PHP, C# i Ruby) używają do uwierzytelniania domyślnych danych logowania aplikacji Google .
    • Aby uwierzytelnić się w środowisku programistycznym, ustaw zmienną środowiskową GOOGLE_APPLICATION_CREDENTIALS tak, aby wskazywała plik klucza konta usługi JSON. Plik klucza można utworzyć na stronie Poświadczenia konsoli interfejsu API .
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • W środowisku produkcyjnym nie musisz się uwierzytelniać, jeśli uruchamiasz swoją aplikację w App Engine lub Compute Engine, korzystając z tego samego projektu, którego używasz w Cloud Firestore. W przeciwnym razie skonfiguruj konto usługi .
  2. Zainstaluj i włącz rozszerzenie gRPC dla PHP, które będzie potrzebne do korzystania z biblioteki klienckiej.
  3. Dodaj bibliotekę PHP Cloud Firestore do swojej aplikacji:
    composer require google/cloud-firestore
C#
  1. Biblioteki klienta serwera Cloud Firestore (Java, Node.js, Python, Go, PHP, C# i Ruby) używają do uwierzytelniania domyślnych danych logowania aplikacji Google .
    • Aby uwierzytelnić się w środowisku programistycznym, ustaw zmienną środowiskową GOOGLE_APPLICATION_CREDENTIALS tak, aby wskazywała plik klucza konta usługi JSON. Plik klucza można utworzyć na stronie Poświadczenia konsoli interfejsu API .
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • W środowisku produkcyjnym nie musisz się uwierzytelniać, jeśli uruchamiasz swoją aplikację w App Engine lub Compute Engine, korzystając z tego samego projektu, którego używasz w Cloud Firestore. W przeciwnym razie skonfiguruj konto usługi .
  2. Dodaj bibliotekę Cloud Firestore C# do swojej aplikacji w pliku .csproj :
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  3. Dodaj następujące elementy do pliku Program.cs :
    using Google.Cloud.Firestore;
Rubin
  1. Biblioteki klienta serwera Cloud Firestore (Java, Node.js, Python, Go, PHP, C# i Ruby) używają do uwierzytelniania domyślnych danych logowania aplikacji Google .
    • Aby uwierzytelnić się w środowisku programistycznym, ustaw zmienną środowiskową GOOGLE_APPLICATION_CREDENTIALS tak, aby wskazywała plik klucza konta usługi JSON. Plik klucza można utworzyć na stronie Poświadczenia konsoli interfejsu API .
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • W środowisku produkcyjnym nie musisz się uwierzytelniać, jeśli uruchamiasz swoją aplikację w App Engine lub Compute Engine, korzystając z tego samego projektu, którego używasz w Cloud Firestore. W przeciwnym razie skonfiguruj konto usługi .
  2. Dodaj bibliotekę Cloud Firestore Ruby do swojej aplikacji w Gemfile :
    gem "google-cloud-firestore"
  3. Zainstaluj zależności z pliku Gemfile , używając:
    bundle install

(Opcjonalnie) Prototypuj i testuj za pomocą Firebase Local Emulator Suite

Deweloperzy mobilni, zanim porozmawiamy o tym, jak Twoja aplikacja zapisuje i odczytuje z Cloud Firestore, przedstawimy zestaw narzędzi, których możesz użyć do prototypowania i testowania funkcjonalności Cloud Firestore: Firebase Local Emulator Suite. Jeśli wypróbowujesz różne modele danych, optymalizujesz reguły bezpieczeństwa lub pracujesz nad znalezieniem najbardziej opłacalnego sposobu interakcji z zapleczem, możliwość pracy lokalnej bez wdrażania usług na żywo może być świetnym pomysłem.

Emulator Cloud Firestore jest częścią pakietu Local Emulator Suite, który umożliwia Twojej aplikacji interakcję z zawartością i konfiguracją emulowanej bazy danych, a także opcjonalnie emulowanymi zasobami projektu (funkcjami, innymi bazami danych i regułami bezpieczeństwa).

Korzystanie z emulatora Cloud Firestore obejmuje tylko kilka kroków:

  1. Dodanie wiersza kodu do konfiguracji testowej aplikacji w celu nawiązania połączenia z emulatorem.
  2. Z katalogu głównego lokalnego katalogu projektu, uruchamiając firebase emulators:start .
  3. Wykonywanie wywołań z kodu prototypu aplikacji przy użyciu pakietu SDK platformy Cloud Firestore w zwykły sposób.

Dostępny jest szczegółowy przewodnik dotyczący Cloud Firestore i Cloud Functions . Warto również zapoznać się z wprowadzeniem do pakietu Local Emulator Suite .

Zainicjuj Cloud Firestore

Zainicjuj instancję Cloud Firestore:

Web modular API

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);

Zamień FIREBASE_CONFIGURATION na firebaseConfig swojej aplikacji internetowej.

Aby zachować dane, gdy urządzenie utraci połączenie, zapoznaj się z dokumentacją Włącz dane offline .

Web namespaced API

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();

Zamień FIREBASE_CONFIGURATION na firebaseConfig swojej aplikacji internetowej.

Aby zachować dane, gdy urządzenie utraci połączenie, zapoznaj się z dokumentacją Włącz dane offline .

Szybki
Uwaga: ten produkt nie jest dostępny w docelowych systemach watchOS i App Clip.
import FirebaseCore
import FirebaseFirestore
FirebaseApp.configure()

let db = Firestore.firestore()
Cel C
Uwaga: ten produkt nie jest dostępny w docelowych systemach watchOS i App Clip.
@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;
Jawa
Zestaw Cloud Firestore SDK jest inicjowany na różne sposoby w zależności od środowiska. Poniżej znajdują się najpopularniejsze metody. Pełne informacje znajdziesz w artykule Inicjowanie pakietu Admin SDK .
  • Zainicjuj w Google Cloud
    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();
    
  • Zainicjuj na własnym serwerze

    Aby używać Firebase Admin SDK na własnym serwerze, użyj konta usługi .

    Przejdź do sekcji Uprawnienia i administrator > Konta usług w konsoli Google Cloud. Wygeneruj nowy klucz prywatny i zapisz plik JSON. Następnie użyj pliku do zainicjowania zestawu 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();
    
  • Pyton
    Zestaw Cloud Firestore SDK jest inicjowany na różne sposoby w zależności od środowiska. Poniżej znajdują się najpopularniejsze metody. Pełne informacje znajdziesz w artykule Inicjowanie pakietu Admin SDK .
  • Zainicjuj w Google Cloud
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()

    Do zainicjowania zestawu SDK można również użyć istniejących domyślnych poświadczeń aplikacji.

    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()
  • Zainicjuj na własnym serwerze

    Aby używać Firebase Admin SDK na własnym serwerze, użyj konta usługi .

    Przejdź do sekcji Uprawnienia i administrator > Konta usług w konsoli Google Cloud. Wygeneruj nowy klucz prywatny i zapisz plik JSON. Następnie użyj pliku do zainicjowania zestawu 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

    Zestaw Cloud Firestore SDK jest inicjowany na różne sposoby w zależności od środowiska. Poniżej znajdują się najpopularniejsze metody. Pełne informacje znajdziesz w artykule Inicjowanie pakietu Admin SDK .
  • Zainicjuj w Google Cloud
    import firebase_admin
    from firebase_admin import firestore_async
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore_async.client()

    Do zainicjowania zestawu SDK można również użyć istniejących domyślnych poświadczeń aplikacji.

    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()
  • Zainicjuj na własnym serwerze

    Aby używać Firebase Admin SDK na własnym serwerze, użyj konta usługi .

    Przejdź do sekcji Uprawnienia i administrator > Konta usług w konsoli Google Cloud. Wygeneruj nowy klucz prywatny i zapisz plik JSON. Następnie użyj pliku do zainicjowania zestawu 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
    Zestaw Cloud Firestore SDK jest inicjowany na różne sposoby w zależności od środowiska. Poniżej znajdują się najpopularniejsze metody. Pełne informacje znajdziesz w artykule Inicjowanie pakietu Admin SDK .
    • Zainicjuj w Cloud Functions
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
    • Zainicjuj w 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();
    • Zainicjuj na własnym serwerze

      Aby korzystać z Firebase Admin SDK na własnym serwerze (lub innym środowisku Node.js), użyj konta usługi . Przejdź do sekcji Uprawnienia i administrator > Konta usług w konsoli Google Cloud. Wygeneruj nowy klucz prywatny i zapisz plik JSON. Następnie użyj pliku do zainicjowania zestawu 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();
      
    Iść
    Zestaw Cloud Firestore SDK jest inicjowany na różne sposoby w zależności od środowiska. Poniżej znajdują się najpopularniejsze metody. Pełne informacje znajdziesz w artykule Inicjowanie pakietu Admin SDK .
  • Zainicjuj w Google Cloud
    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()
    
  • Zainicjuj na własnym serwerze

    Aby używać Firebase Admin SDK na własnym serwerze, użyj konta usługi .

    Przejdź do sekcji Uprawnienia i administrator > Konta usług w konsoli Google Cloud. Wygeneruj nowy klucz prywatny i zapisz plik JSON. Następnie użyj pliku do zainicjowania zestawu 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

    Aby uzyskać więcej informacji na temat instalowania i tworzenia klienta Cloud Firestore, zapoznaj się z Bibliotekami klienta Cloud Firestore .

    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);
        }
    }
    Jedność
    using Firebase.Firestore;
    using Firebase.Extensions;
    FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
    C#

    C#

    Aby uzyskać więcej informacji na temat instalowania i tworzenia klienta Cloud Firestore, zapoznaj się z Bibliotekami klienta Cloud Firestore .

    FirestoreDb db = FirestoreDb.Create(project);
    Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
    Rubin
    require "google/cloud/firestore"
    
    # The `project_id` 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.
    firestore = Google::Cloud::Firestore.new project_id: project_id
    
    puts "Created Cloud Firestore client with given project ID."

    Dodaj dane

    Cloud Firestore przechowuje dane w Dokumentach, które są przechowywane w Kolekcjach. Cloud Firestore tworzy kolekcje i dokumenty niejawnie przy pierwszym dodaniu danych do dokumentu. Nie trzeba jawnie tworzyć kolekcji ani dokumentów.

    Utwórz nową kolekcję i dokument przy użyciu następującego przykładowego kodu.

    Web modular API

    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 namespaced API

    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);
    });
    Szybki
    Uwaga: ten produkt nie jest dostępny w docelowych systemach watchOS i App Clip.
    // 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)")
        }
    }
    Cel C
    Uwaga: ten produkt nie jest dostępny w docelowych systemach watchOS i App Clip.
    // 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}'));
    Jawa
    DocumentReference docRef = db.collection("users").document("alovelace");
    // Add document data  with id "alovelace" using a hashmap
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Ada");
    data.put("last", "Lovelace");
    data.put("born", 1815);
    //asynchronously write data
    ApiFuture<WriteResult> result = docRef.set(data);
    // ...
    // result.get() blocks on response
    System.out.println("Update time : " + result.get().getUpdateTime());
    Pyton
    doc_ref = db.collection('users').document('alovelace')
    doc_ref.set({
        'first': 'Ada',
        'last': 'Lovelace',
        'born': 1815
    })

    Python

    doc_ref = db.collection("users").document("alovelace")
    await doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})
    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
    const docRef = db.collection('users').doc('alovelace');
    
    await docRef.set({
      first: 'Ada',
      last: 'Lovelace',
      born: 1815
    });
    Iść
    _, _, err := client.Collection("users").Add(ctx, map[string]interface{}{
    	"first": "Ada",
    	"last":  "Lovelace",
    	"born":  1815,
    })
    if err != nil {
    	log.Fatalf("Failed adding alovelace: %v", err)
    }
    PHP

    PHP

    Aby uzyskać więcej informacji na temat instalowania i tworzenia klienta Cloud Firestore, zapoznaj się z Bibliotekami klienta Cloud Firestore .

    $docRef = $db->collection('samples/php/users')->document('alovelace');
    $docRef->set([
        'first' => 'Ada',
        'last' => 'Lovelace',
        'born' => 1815
    ]);
    printf('Added data to the lovelace document in the users collection.' . PHP_EOL);
    Jedność
    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);
    Rubin
    doc_ref = firestore.doc "#{collection_path}/alovelace"
    
    doc_ref.set(
      {
        first: "Ada",
        last:  "Lovelace",
        born:  1815
      }
    )
    
    puts "Added data to the alovelace document in the users collection."

    Teraz dodaj kolejny dokument do kolekcji users . Zwróć uwagę, że ten dokument zawiera parę klucz-wartość (drugie imię), która nie pojawia się w pierwszym dokumencie. Dokumenty w kolekcji mogą zawierać różne zestawy informacji.

    Web modular API

    // 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 namespaced API

    // 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);
    });
    Szybki
    Uwaga: ten produkt nie jest dostępny w docelowych systemach watchOS i App Clip.
    // 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)")
        }
    }
    Cel C
    Uwaga: ten produkt nie jest dostępny w docelowych systemach watchOS i App Clip.
    // 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}'));
    Jawa
    DocumentReference docRef = db.collection("users").document("aturing");
    // Add document data with an additional field ("middle")
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Alan");
    data.put("middle", "Mathison");
    data.put("last", "Turing");
    data.put("born", 1912);
    
    ApiFuture<WriteResult> result = docRef.set(data);
    System.out.println("Update time : " + result.get().getUpdateTime());
    Pyton
    doc_ref = db.collection('users').document('aturing')
    doc_ref.set({
        'first': 'Alan',
        'middle': 'Mathison',
        'last': 'Turing',
        'born': 1912
    })

    Python

    doc_ref = db.collection("users").document("aturing")
    await doc_ref.set(
        {"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912}
    )
    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
    const aTuringRef = db.collection('users').doc('aturing');
    
    await aTuringRef.set({
      'first': 'Alan',
      'middle': 'Mathison',
      'last': 'Turing',
      'born': 1912
    });
    Iść
    _, _, err = client.Collection("users").Add(ctx, map[string]interface{}{
    	"first":  "Alan",
    	"middle": "Mathison",
    	"last":   "Turing",
    	"born":   1912,
    })
    if err != nil {
    	log.Fatalf("Failed adding aturing: %v", err)
    }
    PHP

    PHP

    Aby uzyskać więcej informacji na temat instalowania i tworzenia klienta Cloud Firestore, zapoznaj się z Bibliotekami klienta Cloud Firestore .

    $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);
    Jedność
    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);
    Rubin
    doc_ref = firestore.doc "#{collection_path}/aturing"
    
    doc_ref.set(
      {
        first:  "Alan",
        middle: "Mathison",
        last:   "Turing",
        born:   1912
      }
    )
    
    puts "Added data to the aturing document in the users collection."

    Odczyt danych

    Użyj przeglądarki danych w konsoli Firebase , aby szybko sprawdzić, czy dane zostały dodane do Cloud Firestore.

    Możesz także użyć metody „get”, aby pobrać całą kolekcję.

    Web modular API

    import { collection, getDocs } from "firebase/firestore"; 
    
    const querySnapshot = await getDocs(collection(db, "users"));
    querySnapshot.forEach((doc) => {
      console.log(`${doc.id} => ${doc.data()}`);
    });

    Web namespaced API

    db.collection("users").get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            console.log(`${doc.id} => ${doc.data()}`);
        });
    });
    Szybki
    Uwaga: ten produkt nie jest dostępny w docelowych systemach watchOS i App Clip.
    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())")
            }
        }
    }
    Cel C
    Uwaga: ten produkt nie jest dostępny w docelowych systemach watchOS i App Clip.
    [[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()}");
      }
    });
    Jawa
    // asynchronously retrieve all users
    ApiFuture<QuerySnapshot> query = db.collection("users").get();
    // ...
    // query.get() blocks on response
    QuerySnapshot querySnapshot = query.get();
    List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      System.out.println("User: " + document.getId());
      System.out.println("First: " + document.getString("first"));
      if (document.contains("middle")) {
        System.out.println("Middle: " + document.getString("middle"));
      }
      System.out.println("Last: " + document.getString("last"));
      System.out.println("Born: " + document.getLong("born"));
    }
    Pyton
    users_ref = db.collection('users')
    docs = users_ref.stream()
    
    for doc in docs:
        print(f'{doc.id} => {doc.to_dict()}')

    Python

    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    async for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")
    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
    const snapshot = await db.collection('users').get();
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
    Iść
    iter := client.Collection("users").Documents(ctx)
    for {
    	doc, err := iter.Next()
    	if err == iterator.Done {
    		break
    	}
    	if err != nil {
    		log.Fatalf("Failed to iterate: %v", err)
    	}
    	fmt.Println(doc.Data())
    }
    PHP

    PHP

    Aby uzyskać więcej informacji na temat instalowania i tworzenia klienta Cloud Firestore, zapoznaj się z Bibliotekami klienta Cloud Firestore .

    $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);
    Jedność
    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();
    }
    Rubin
    users_ref = firestore.col collection_path
    users_ref.get do |user|
      puts "#{user.document_id} data: #{user.data}."
    end

    Zabezpiecz swoje dane

    Jeśli korzystasz z pakietu SDK platformy Web, Android lub Apple, użyj uwierzytelniania Firebase i zasad bezpieczeństwa Cloud Firestore , aby zabezpieczyć swoje dane w Cloud Firestore.

    Oto kilka podstawowych zestawów reguł, których możesz użyć na początek. Możesz zmodyfikować swoje reguły bezpieczeństwa na karcie Reguły w konsoli.

    Wymagana autoryzacja

    // 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;
        }
      }
    }
    

    Tryb zablokowany

    // Deny read/write access to all users under any conditions
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if false;
        }
      }
    }
    

    Tryb testowania

    // 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;
        }
      }
    }
    

    Przed wdrożeniem aplikacji internetowej, aplikacji na Androida lub iOS w środowisku produkcyjnym podejmij także kroki, aby upewnić się, że tylko klienci Twojej aplikacji będą mieli dostęp do Twoich danych Cloud Firestore. Zobacz dokumentację sprawdzania aplikacji .

    Jeśli używasz jednego z zestawów SDK serwera, użyj zarządzania tożsamościami i dostępem (IAM), aby zabezpieczyć swoje dane w Cloud Firestore.

    Obejrzyj samouczek wideo

    Aby uzyskać szczegółowe wskazówki dotyczące rozpoczynania pracy z bibliotekami klienta mobilnego Cloud Firestore, obejrzyj jeden z następujących samouczków wideo:

    Sieć
    iOS+
    Android

    Więcej filmów znajdziesz na kanale Firebase na YouTube .

    Następne kroki

    Pogłębiaj swoją wiedzę o następujące tematy: