תחילת העבודה עם Cloud Firestore

במדריך למתחילים הזה מוסבר איך להגדיר את Cloud Firestore, להוסיף נתונים ולהציג על הנתונים שהוספתם עכשיו במסוף Firebase.

יצירת מסד נתונים של Cloud Firestore

  1. אם עדיין לא עשיתם זאת, יוצרים פרויקט Firebase: בקטע במסוף Firebase, לוחצים על הוספת פרויקט. אחר כך פועלים לפי ההוראות במסך כדי ליצור פרויקט Firebase או להוסיף שירותי Firebase לפרויקט GCP קיים.

  2. עוברים לקטע Cloud Firestore מסוף Firebase. תתבקשו לבחור פרויקט קיים ב-Firebase. לפעול לפי תהליך העבודה ליצירת מסד נתונים.

  3. צריך לבחור מצב התחלה עבור Cloud Firestore Security Rules:

    מצב בדיקה

    מתאימים לתחילת העבודה עם ספריות לקוח לנייד ולאינטרנט, אבל הוא מאפשר לכל אחד לקרוא ולהחליף את הנתונים שלכם. לאחר הבדיקה, מבצעים חשוב לעיין בקטע אבטחת הנתונים.

    כדי להתחיל לעבוד עם מערכות אינטרנט, פלטפורמות של Apple או Android SDK, צריך לבחור באפשרות 'מצב בדיקה'.

    מצב נעילה

    דוחה את כל פעולות הקריאה והכתיבה ללקוחות בנייד ובאינטרנט. שרתי האפליקציות המאומתים שלכם (C#, Go, Java, Node.js, PHP, Python או Ruby) עדיין יכולים לגשת למסד הנתונים.

    כדי להתחיל לעבוד עם #C, Go, Java, Node.js, PHP, Python או Ruby יש לבחור במצב נעילה.

    הקבוצה הראשונית של Cloud Firestore Security Rules תחול על ברירת המחדל מסד הנתונים Cloud Firestore. אם אתם יוצרים כמה מסדי נתונים בפרויקט, אפשר לפרוס את Cloud Firestore Security Rules לכל מסד נתונים.

  4. בוחרים מיקום למסד הנתונים.

    • הגדרת המיקום הזו היא של הפרויקט שלך מיקום ברירת המחדל של משאב ב-Google Cloud Platform (GCP). חשוב לשים לב שהמיקום הזה ישמש לשירותי GCP בפרויקט שלך. שמצריכות הגדרת מיקום, וספציפית, ברירת המחדל הקטגוריה של Cloud Storage אפליקציית App Engine ( נדרש אם משתמשים ב-Cloud Scheduler).

    • אם אין אפשרות לבחור מיקום, סימן שהפרויקט כבר פועל יש לו מיקום משאב GCP כברירת מחדל. הוא הוגדר במהלך יצירת הפרויקט או במהלך הגדרת שירות אחר שדורש הגדרת מיקום.

  5. לוחצים על סיום.

כשמפעילים את Cloud Firestore, הוא מפעיל את ה-API גם Cloud API Manager

הגדרת סביבת הפיתוח

מוסיפים לאפליקציה את יחסי התלות הנדרשים ואת ספריות הלקוח.

Web

  1. פועלים לפי ההוראות כדי מוסיפים את Firebase לאפליקציית האינטרנט.
  2. מוסיפים את ספריות Firebase ו-Cloud Firestore לאפליקציה:
    <script src="https://www.gstatic.com/firebasejs/10.13.1/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.13.1/firebase-firestore-compat.js"></script>
    ערכת ה-SDK של Cloud Firestore זמינה גם כחבילת NPM.
    npm install firebase@10.13.1 --save
    יהיה עליך לדרוש באופן ידני גם את Firebase וגם Cloud Firestore.
    import firebase from "firebase/compat/app";
    // Required for side-effects
    import "firebase/firestore";

Web

  1. פועלים לפי ההוראות כדי מוסיפים את Firebase לאפליקציית האינטרנט.
  2. ה-SDK של Cloud Firestore זמין כחבילת NPM.
    npm install firebase@10.13.1 --save
    צריך לייבא גם את Firebase וגם את Cloud Firestore.
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";
iOS+

פועלים לפי ההוראות כדי מוסיפים את Firebase לאפליקציה ב-Apple.

שימוש ב-Swift Package Manager כדי להתקין ולנהל יחסי תלות של Firebase.

  1. ב-Xcode, כשפרויקט האפליקציה פתוח, עוברים אל File > (קובץ >) חבילות SWIFT > הוספת תלות בחבילה.
  2. כשמופיעה בקשה, מוסיפים את מאגר ה-SDK של מוצרי הפלטפורמה של Firebase של Apple:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. בוחרים את ספריית Firestore.
  5. בסיום, Xcode יתחיל לפתור את הבעיה ותוריד את של יחסי התלות ברקע.
Android
  1. פועלים לפי ההוראות כדי מוסיפים את Firebase לאפליקציה ל-Android.
  2. באמצעות 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:33.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")
    }

    באמצעות Firebase Android BoM, האפליקציה שלך תשתמש תמיד בגרסאות תואמות של גרסת ה-Android של Firebase של הספריות.

    (חלופה) להצהיר על יחסי תלות של ספריית 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:25.1.0")
    }

    מחפשים מודול ספרייה ספציפי ל-Kotlin? מתחיל ב- גרסת אוקטובר 2023, גם מפתחי Kotlin וגם מפתחי Java יכולים להסתמך על מודול הספרייה הראשי (פרטים נוספים זמינים במאמר שאלות נפוצות לגבי היוזמה).

Dart

  1. אם עדיין לא עשיתם זאת, מגדירים ו מפעילים את Firebase באפליקציה Flutter.
  2. מהרמה הבסיסית (root) של פרויקט Flutter, מריצים את הפקודה הבאה כדי מתקינים את הפלאגין:
    flutter pub add cloud_firestore
  3. בסיום, יוצרים מחדש את אפליקציית Flutter:
    flutter run
  4. אופציונלי: כדי לשפר את זמני ה-build של iOS ו-macOS, מוסיפים את המסגרת המתומצתת.

    בשלב הזה, Firestore SDK ל-iOS תלוי בקוד שיכול לקבל לפיתוח של יותר מ-5 דקות ב-Xcode. כדי לקצר את זמני ה-build באופן משמעותי, אפשר להשתמש בגרסה שעברה הידור מראש על ידי הוספת השורה הזו הבלוק target 'Runner' do ב-Podfile:

    target 'Runner' do
      use_frameworks!
      use_modular_headers!
    
      pod 'FirebaseFirestore',
        :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git',
        :tag => 'IOS_SDK_VERSION'
    
      flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
      target 'RunnerTests' do
        inherit! :search_paths
      end
    end

    מחליפים את IOS_SDK_VERSION בגרסת Firebase iOS ערכת ה-SDK שצוינה ב-firebase_core firebase_sdk_version.rb חדש. אם אינך משתמש בגרסה העדכנית של firebase_core, חפש את הקובץ הזה בחבילת ה-Pub המקומית שלך מטמון (בדרך כלל ~/.pub-cache).

    בנוסף, חשוב לוודא ששדרגתם את CocoaPods ל-1.9.1 או גבוהה יותר:

    gem install cocoapods

    מידע נוסף זמין במאמר בעיה ב-GitHub.

Java
  1. מוסיפים את Firebase Admin SDK לאפליקציה:
    • באמצעות Gradle:
      compile 'com.google.firebase:firebase-admin:1.32.0'
    • באמצעות Maven:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>1.32.0</version>
      </dependency>
           
  2. צריך לפעול לפי ההוראות הבאות כדי לאתחל את Cloud Firestore עם פרטי הכניסה המתאימים בסביבה שלכם.
Python
  1. מוסיפים את Firebase Admin SDK לאפליקציית Python:
    pip install --upgrade firebase-admin
  2. צריך לפעול לפי ההוראות הבאות כדי לאתחל את Cloud Firestore עם פרטי הכניסה המתאימים בסביבה שלכם.
C++‎
  1. פועלים לפי ההוראות כדי מוסיפים את Firebase לפרויקט C++.
  2. ממשק 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 file:
              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. כדי להגדיר שילוב במחשב, כדאי לעיין במאמר הוספת Firebase לפרויקט C++.
Unity
  1. פועלים לפי ההוראות כדי הוספת Firebase ל-Unity project.
  2. איך משתמשים בממשק Unity כדי להגדיר את הפרויקט להקטנת גרסאות build של Android.
  3. כדי למנוע את ההודעה Error while merging dex archives, צריך לבצע אופטימיזציה של ה-build.

    • ניתן למצוא את האפשרות הזו בהגדרות הנגן > Android > הוצאה לאור הגדרות > מזעור.
    • האפשרויות עשויות להיות שונות בגרסאות שונות של Unity, לכן כדאי לעיין המסמכים הרשמיים של Unity וגם מדריך לניפוי באגים ב-Firebase Unity Build.
    • אם לאחר הפעלת ההקטנה, מספר השיטות שיש הפניה אליהן עדיין חורגת מהמגבלה, אפשרות נוספת היא להפעיל את multidex ב:
      • mainTemplate.gradle אם האפשרות תבנית Gradle מותאמת אישית בקטע הגדרות נגן מופעלת
      • או את הקובץ build.gradle ברמת המודול, אם משתמשים ב-Android Studio כדי ליצור את הפרויקט המיוצא.
Node.js
  1. מוסיפים את Firebase Admin SDK לאפליקציה:
    npm install firebase-admin --save
  2. צריך לפעול לפי ההוראות הבאות כדי לאתחל את Cloud Firestore עם פרטי הכניסה המתאימים בסביבה שלכם.
Go
  1. מוסיפים את Firebase Admin SDK לאפליקציה ב-Go:
    go get firebase.google.com/go
  2. צריך לפעול לפי ההוראות הבאות כדי לאתחל את Cloud Firestore עם פרטי הכניסה המתאימים בסביבה שלכם.
PHP
  1. ספריות הלקוח של השרת Cloud Firestore (Java , Node.js , Python , Go , PHP , C# ו-Ruby) אישורי ברירת מחדל לאפליקציות של Google לצורך אימות.
    • כדי לבצע אימות מסביבת הפיתוח, מגדירים את משתנה הסביבה GOOGLE_APPLICATION_CREDENTIALS כך שיצביע לקובץ JSON של מפתח חשבון שירות. אפשר ליצור קובץ מפתח בדף פרטי הכניסה של מסוף ה-API.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • בסביבת הייצור, אין צורך לאמת אם אתם מריצים את האפליקציה ב-App Engine או ב-Compute Engine, באמצעות אותו פרויקט שמשמש אותך ל-Cloud Firestore. אחרת, מגדירים חשבון שירות.
  2. מתקינים ומפעילים את התוסף gRPC ל-PHP, שיהיה צורך להשתמש בספריית הלקוח.
  3. מוסיפים את ספריית ה-PHP של Cloud Firestore לאפליקציה:
    composer require google/cloud-firestore
C#‎
  1. ספריות הלקוח של השרת Cloud Firestore (Java , Node.js , Python , Go , PHP , C# ו-Ruby) אישורי ברירת מחדל לאפליקציות של Google לצורך אימות.
    • כדי לבצע אימות מסביבת הפיתוח, מגדירים את משתנה הסביבה GOOGLE_APPLICATION_CREDENTIALS כך שיצביע לקובץ JSON של מפתח חשבון שירות. אפשר ליצור קובץ מפתח בדף פרטי הכניסה של מסוף ה-API.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • בסביבת הייצור, אין צורך לאמת אם אתם מריצים את האפליקציה ב-App Engine או ב-Compute Engine, באמצעות אותו פרויקט שמשמש אותך ל-Cloud Firestore. אחרת, מגדירים חשבון שירות.
  2. מוסיפים את ספריית C# של Cloud Firestore לאפליקציה בקובץ .csproj:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  3. מוסיפים לקובץ Program.cs את הנתונים הבאים:
    using Google.Cloud.Firestore;
Ruby
  1. ספריות הלקוח של השרת Cloud Firestore (Java , Node.js , Python , Go , PHP , C# ו-Ruby) אישורי ברירת מחדל לאפליקציות של Google לצורך אימות.
    • כדי לבצע אימות מסביבת הפיתוח, מגדירים את GOOGLE_APPLICATION_CREDENTIALS שיצביע על קובץ מפתח של חשבון שירות בפורמט JSON. אפשר ליצור קובץ מפתח בדף פרטי הכניסה של מסוף ה-API.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • בסביבת הייצור, אין צורך לאמת אם אתם מריצים את האפליקציה ב-App Engine או ב-Compute Engine, באמצעות אותו פרויקט שמשמש אותך ל-Cloud Firestore. אחרת, מגדירים חשבון שירות.
  2. מוסיפים את ספריית Cloud Firestore Ruby לאפליקציה ב-Gemfile:
    gem "google-cloud-firestore"
  3. מתקינים את יחסי התלות מ-Gemfile באמצעות:
    bundle install

(אופציונלי) אב-טיפוס ובדיקה באמצעות Firebase Local Emulator Suite

למפתחים לנייד: לפני שתדברו על האופן שבו האפליקציה כותבת וקוראת מתוך Cloud Firestore, בואו נציג ערכת כלים שתוכלו להשתמש בהם אב טיפוס ובדיקת הפונקציונליות של Cloud Firestore: Firebase Local Emulator Suite. אם אתם מנסים מודלים שונים של נתונים, לבצע אופטימיזציה של כללי האבטחה שלכם, או למצוא את הדרך המשתלמת ביותר לקיים אינטראקציה עם הקצה העורפי, יכולת לעבוד באופן מקומי ללא פריסה שירותים בשידור חי יכולים להיות רעיון מעולה.

אמולטור Cloud Firestore הוא חלק מ-Local Emulator Suite, מאפשרת לאפליקציה לבצע פעולות באמולציה של התוכן של מסד הנתונים ושל ההגדרות שלו, כמו וגם באופן אופציונלי את משאבי הפרויקט האמולציה (פונקציות, מסדי נתונים אחרים, וכללי אבטחה).

כדי להשתמש באמולטור Cloud Firestore יש כמה שלבים פשוטים:

  1. הוספה של שורת קוד להגדרות הבדיקה של האפליקציה כדי להתחבר לאמולטור.
  2. מהרמה הבסיסית (root) של ספריית הפרויקט המקומית, מריצים את firebase emulators:start.
  3. ביצוע שיחות מקוד אב הטיפוס של האפליקציה באמצעות פלטפורמת Cloud Firestore SDK כרגיל.

יש הדרכה מפורטת בנושא 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.

כדי לשמור נתונים כאשר המכשיר מאבד את החיבור, עיין במסמכים בנושא הפעלת נתונים במצב אופליין.

Swift
הערה: המוצר הזה לא זמין ביעדים מסוגwatchOS ו-קליפ של אפליקציה.
import FirebaseCore
import FirebaseFirestore
FirebaseApp.configure()

let db = Firestore.firestore()
Objective-C
הערה: המוצר הזה לא זמין ביעדים מסוגwatchOS ו-קליפ של אפליקציה.
@import FirebaseCore;
@import FirebaseFirestore;

// Use Firebase library to configure APIs
[FIRApp configure];
  
FIRFirestore *defaultFirestore = [FIRFirestore firestore];

Kotlin+KTX

// Access a Cloud Firestore instance from your Activity
val db = Firebase.firestore

Java

// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();

Dart

db = FirebaseFirestore.instance;
Java
ה-SDK של Cloud Firestore מופעל בדרכים שונות, בהתאם ל: בסביבה שלך. בהמשך מפורטות השיטות הכי נפוצות. לידיעתך, לראות אתחול Admin SDK.
  • איפוס ב-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();
  • אתחול בשרת שלכם

    כדי להשתמש ב-Firebase Admin SDK בשרת שלכם, צריך להשתמש ב- חשבון שירות.

    מעבר אל IAM & אדמין > חשבונות שירות במסוף Google Cloud. יצירת מפתח פרטי חדש ושמירת קובץ ה-JSON חדש. לאחר מכן משתמשים בקובץ כדי לאתחל את ה-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
    ה-SDK של Cloud Firestore מופעל בדרכים שונות, בהתאם ל: בסביבה שלך. בהמשך מפורטות השיטות הכי נפוצות. לידיעתך, לראות אתחול Admin SDK.
  • אתחול ב-Google Cloud
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()

    אפשר להשתמש בפרטי כניסה קיימים שמוגדרים כברירת מחדל גם כדי לאתחל את ה-SDK.

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore.client()
  • אתחול בשרת שלכם

    כדי להשתמש ב-Firebase Admin SDK בשרת שלכם, צריך להשתמש ב- חשבון שירות.

    מעבר אל IAM & אדמין > חשבונות שירות במסוף Google Cloud. יצירת מפתח פרטי חדש ושמירת קובץ ה-JSON חדש. לאחר מכן משתמשים בקובץ כדי לאתחל את ה-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

    ה-SDK של Cloud Firestore מופעל בדרכים שונות, בהתאם ל: בסביבה שלך. בהמשך מפורטות השיטות הכי נפוצות. לידיעתך, לראות אתחול Admin SDK.
  • איפוס ב-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()

    אפשר להשתמש בפרטי כניסה קיימים שמוגדרים כברירת מחדל גם כדי לאתחל את ה-SDK.

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore_async.client()
  • איך מפעילים את השירות בשרת משלכם

    כדי להשתמש ב-Firebase Admin SDK בשרת שלכם, צריך להשתמש ב- חשבון שירות.

    מעבר אל IAM & אדמין > חשבונות שירות במסוף Google Cloud. יצירת מפתח פרטי חדש ושמירת קובץ ה-JSON חדש. לאחר מכן משתמשים בקובץ כדי לאתחל את ה-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
    ה-SDK של Cloud Firestore מופעל בדרכים שונות, בהתאם ל: בסביבה שלך. בהמשך מפורטות השיטות הכי נפוצות. לידיעתך, לראות אתחול Admin SDK.
    • אתחול ב-Cloud Functions
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
    • אתחול ב-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();
    • איך מפעילים את השירות בשרת משלכם

      כדי להשתמש ב-Firebase Admin SDK בשרת שלכם (או בכל סביבת Node.js אחרת), משתמשים בחשבון שירות. למעבר אל IAM & אדמין > חשבונות שירות במסוף Google Cloud. יוצרים מפתח פרטי חדש ושומרים את קובץ ה-JSON. לאחר מכן משתמשים בקובץ כדי לאתחל את ה-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();
      
    Go
    ה-SDK של Cloud Firestore מופעל בדרכים שונות, בהתאם ל: בסביבה שלך. בהמשך מפורטות השיטות הכי נפוצות. לידיעתך, לראות אתחול Admin SDK.
  • איפוס ב-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()
  • איך מפעילים את השירות בשרת משלכם

    כדי להשתמש ב-Firebase Admin SDK בשרת שלכם, צריך להשתמש ב- חשבון שירות.

    מעבר אל IAM & אדמין > חשבונות שירות במסוף Google Cloud. יוצרים מפתח פרטי חדש ושומרים את קובץ ה-JSON. לאחר מכן משתמשים בקובץ כדי לאתחל את ה-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

    מידע נוסף על התקנה ויצירה של לקוח Cloud Firestore זמין ב- 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);
        }
    }
    Unity
    using Firebase.Firestore;
    using Firebase.Extensions;
    FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
    C#‎

    C#‎

    מידע נוסף על התקנה ויצירה של לקוח Cloud Firestore זמין במאמר ספריות לקוח של Cloud Firestore.

    FirestoreDb db = FirestoreDb.Create(project);
    Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
    Ruby
    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."

    הוספת נתונים

    ב-Cloud Firestore הנתונים נשמרים במסמכים שמאוחסנים באוספים. Cloud Firestore יוצר אוספים ומסמכים באופן מרומז בפעם הראשונה שמוסיפים נתונים למסמך. את לא צריכה להגדיר במפורש ליצור אוספים או מסמכים.

    אפשר ליצור אוסף חדש ומסמך באמצעות הקוד הבא לדוגמה.

    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);
    });
    Swift
    הערה: המוצר הזה לא זמין ביעדים מסוגwatchOS ו-קליפ של אפליקציה.
    // 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
    הערה: המוצר הזה לא זמין ביעדים מסוגwatchOS ו-קליפ של אפליקציה.
    // Add a new document with a generated ID
    __block FIRDocumentReference *ref =
        [[self.db collectionWithPath:@"users"] addDocumentWithData:@{
          @"first": @"Ada",
          @"last": @"Lovelace",
          @"born": @1815
        } completion:^(NSError * _Nullable error) {
          if (error != nil) {
            NSLog(@"Error adding document: %@", error);
          } else {
            NSLog(@"Document added with ID: %@", ref.documentID);
          }
        }];

    Kotlin+KTX

    // Create a new user with a first and last name
    val user = hashMapOf(
        "first" to "Ada",
        "last" to "Lovelace",
        "born" to 1815,
    )
    
    // Add a new document with a generated ID
    db.collection("users")
        .add(user)
        .addOnSuccessListener { documentReference ->
            Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
        }
        .addOnFailureListener { e ->
            Log.w(TAG, "Error adding document", e)
        }

    Java

    // Create a new user with a first and last name
    Map<String, Object> user = new HashMap<>();
    user.put("first", "Ada");
    user.put("last", "Lovelace");
    user.put("born", 1815);
    
    // Add a new document with a generated ID
    db.collection("users")
            .add(user)
            .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                @Override
                public void onSuccess(DocumentReference documentReference) {
                    Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "Error adding document", e);
                }
            });

    Dart

    // Create a new user with a first and last name
    final user = <String, dynamic>{
      "first": "Ada",
      "last": "Lovelace",
      "born": 1815
    };
    
    // Add a new document with a generated ID
    db.collection("users").add(user).then((DocumentReference doc) =>
        print('DocumentSnapshot added with ID: ${doc.id}'));
    Java
    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());
    Python
    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
    });
    Go
    _, _, 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

    מידע נוסף על התקנה ויצירה של לקוח Cloud Firestore זמין ב- 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);
    Unity
    DocumentReference docRef = db.Collection("users").Document("alovelace");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
    	{ "First", "Ada" },
    	{ "Last", "Lovelace" },
    	{ "Born", 1815 },
    };
    docRef.SetAsync(user).ContinueWithOnMainThread(task => {
    	Debug.Log("Added data to the alovelace document in the users collection.");
    });
    C#‎
    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
    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."

    עכשיו צריך להוסיף עוד מסמך לאוסף users. שימו לב שהמסמך הזה כולל צמד מפתח/ערך (שם אמצעי) שלא מופיע מהמסמך. מסמכים באוסף יכולים להכיל קבוצות שונות של מידע.

    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);
    });
    Swift
    הערה: המוצר הזה לא זמין ביעדים מסוגwatchOS ו-קליפ של אפליקציה.
    // 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
    הערה: המוצר הזה לא זמין ביעדים מסוגwatchOS ו-קליפ של אפליקציה.
    // Add a second document with a generated ID.
    __block FIRDocumentReference *ref =
        [[self.db collectionWithPath:@"users"] addDocumentWithData:@{
          @"first": @"Alan",
          @"middle": @"Mathison",
          @"last": @"Turing",
          @"born": @1912
        } completion:^(NSError * _Nullable error) {
          if (error != nil) {
            NSLog(@"Error adding document: %@", error);
          } else {
            NSLog(@"Document added with ID: %@", ref.documentID);
          }
        }];

    Kotlin+KTX

    // Create a new user with a first, middle, and last name
    val user = hashMapOf(
        "first" to "Alan",
        "middle" to "Mathison",
        "last" to "Turing",
        "born" to 1912,
    )
    
    // Add a new document with a generated ID
    db.collection("users")
        .add(user)
        .addOnSuccessListener { documentReference ->
            Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
        }
        .addOnFailureListener { e ->
            Log.w(TAG, "Error adding document", e)
        }

    Java

    // Create a new user with a first, middle, and last name
    Map<String, Object> user = new HashMap<>();
    user.put("first", "Alan");
    user.put("middle", "Mathison");
    user.put("last", "Turing");
    user.put("born", 1912);
    
    // Add a new document with a generated ID
    db.collection("users")
            .add(user)
            .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                @Override
                public void onSuccess(DocumentReference documentReference) {
                    Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "Error adding document", e);
                }
            });

    Dart

    // Create a new user with a first and last name
    final user = <String, dynamic>{
      "first": "Alan",
      "middle": "Mathison",
      "last": "Turing",
      "born": 1912
    };
    
    // Add a new document with a generated ID
    db.collection("users").add(user).then((DocumentReference doc) =>
        print('DocumentSnapshot added with ID: ${doc.id}'));
    Java
    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());
    Python
    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
    });
    Go
    _, _, 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

    מידע נוסף על התקנה ויצירה של לקוח Cloud Firestore זמין במאמר ספריות לקוח של 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);
    Unity
    DocumentReference docRef = db.Collection("users").Document("aturing");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
    	{ "First", "Alan" },
    	{ "Middle", "Mathison" },
    	{ "Last", "Turing" },
    	{ "Born", 1912 }
    };
    docRef.SetAsync(user).ContinueWithOnMainThread(task => {
    	Debug.Log("Added data to the aturing document in the users collection.");
    });
    C#‎
    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
    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."

    קריאת נתונים

    אפשר להשתמש ב-Data Viewer במסוף 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()}`);
        });
    });
    Swift
    הערה: המוצר הזה לא זמין ביעדים מסוגwatchOS ו-קליפ של אפליקציה.
    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
    הערה: המוצר הזה לא זמין ביעדים מסוגwatchOS ו-קליפ של אפליקציה.
    [[self.db collectionWithPath:@"users"]
        getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot,
                                     NSError * _Nullable error) {
          if (error != nil) {
            NSLog(@"Error getting documents: %@", error);
          } else {
            for (FIRDocumentSnapshot *document in snapshot.documents) {
              NSLog(@"%@ => %@", document.documentID, document.data);
            }
          }
        }];

    Kotlin+KTX

    db.collection("users")
        .get()
        .addOnSuccessListener { result ->
            for (document in result) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.w(TAG, "Error getting documents.", exception)
        }

    Java

    db.collection("users")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(TAG, document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.w(TAG, "Error getting documents.", task.getException());
                    }
                }
            });

    Dart

    await db.collection("users").get().then((event) {
      for (var doc in event.docs) {
        print("${doc.id} => ${doc.data()}");
      }
    });
    Java
    // 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"));
    }
    Python
    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());
    });
    Go
    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

    מידע נוסף על התקנה ויצירה של לקוח Cloud Firestore זמין ב- 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);
    Unity
    CollectionReference usersRef = db.Collection("users");
    usersRef.GetSnapshotAsync().ContinueWithOnMainThread(task =>
    {
      QuerySnapshot snapshot = task.Result;
      foreach (DocumentSnapshot document in snapshot.Documents)
      {
        Debug.Log(String.Format("User: {0}", document.Id));
        Dictionary<string, object> documentDictionary = document.ToDictionary();
        Debug.Log(String.Format("First: {0}", documentDictionary["First"]));
        if (documentDictionary.ContainsKey("Middle"))
        {
          Debug.Log(String.Format("Middle: {0}", documentDictionary["Middle"]));
        }
    
        Debug.Log(String.Format("Last: {0}", documentDictionary["Last"]));
        Debug.Log(String.Format("Born: {0}", documentDictionary["Born"]));
      }
    
      Debug.Log("Read all data from the users collection.");
    });
    C#‎
    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
    users_ref = firestore.col collection_path
    users_ref.get do |user|
      puts "#{user.document_id} data: #{user.data}."
    end

    אבטחת הנתונים

    אם אתם משתמשים ב-SDK לאינטרנט, ל-Android או לפלטפורמות של Apple, תוכלו להשתמש ב-Firebase Authentication וב-Cloud Firestore Security Rules כדי לאבטח את הנתונים ב-Cloud 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) (IAM) כדי לאבטח את הנתונים שלכם ב-Cloud Firestore.

    לצפייה בסרטון הדרכה

    לקבלת הנחיות מפורטות לתחילת העבודה עם Cloud Firestore ספריות לקוח לנייד, אפשר לצפות באחד מסרטוני ההדרכה הבאים:

    אינטרנט
    iOS+
    Android

    אפשר למצוא סרטונים נוספים ב-Firebase ערוץ ב-YouTube.

    השלבים הבאים

    להעמיק את הידע בנושאים הבאים: