התחל עם Cloud Firestore

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

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

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

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

  3. בחר מצב התחלה עבור כללי האבטחה של Cloud Firestore שלך:

    מצב מבחן

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

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

    מצב נעול

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

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

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

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

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

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

הגדר את סביבת הפיתוח שלך

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

Web namespaced API

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

Web modular API

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

עקוב אחר ההוראות להוספת Firebase לאפליקציית Apple שלך .

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

  1. ב-Xcode, כשפרויקט האפליקציה שלך פתוח, נווט אל קובץ > חבילות Swift > הוסף תלות בחבילה .
  2. כשתתבקש, הוסף את מאגר Firebase Apple platforms SDK:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. בחר את ספריית Firestore.
  5. בסיום, Xcode יתחיל באופן אוטומטי לפתור ולהוריד את התלות שלך ברקע.
דְמוּי אָדָם
  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:32.7.4"))
    
        // Declare the dependency for the Cloud Firestore library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore")
    }
    

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

    (אלטרנטיבי) הכרזה על תלות בספריית Firebase מבלי להשתמש ב-BoM

    אם תבחר שלא להשתמש ב-Firebase BoM, עליך לציין כל גרסת ספריית Firebase בשורת התלות שלה.

    שים לב שאם אתה משתמש במספר ספריות Firebase באפליקציה שלך, אנו ממליצים בחום להשתמש ב-BoM לניהול גרסאות ספרייה, מה שמבטיח שכל הגרסאות תואמות.

    dependencies {
        // Declare the dependency for the Cloud Firestore library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore:24.10.3")
    }
    

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

Dart

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

    נכון לעכשיו, ה-SDK של Firestore עבור iOS תלוי בקוד שיכול לקחת יותר מ-5 דקות לבנות ב-Xcode. כדי לצמצם את זמני הבנייה באופן משמעותי, אתה יכול להשתמש בגרסה המורכבת מראש על ידי הוספת שורה זו לבלוק target 'Runner' do in 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_sdk_version.rb של firebase_core . אם אינך משתמש בגרסה העדכנית ביותר של 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 עם האישורים המתאימים בסביבה שלך.
פִּיתוֹן
  1. הוסף את Firebase Admin SDK לאפליקציית Python שלך:
    pip install --upgrade firebase-admin
  2. בצע את ההוראות שלהלן כדי לאתחל את Cloud Firestore עם האישורים המתאימים בסביבה שלך.
C++
  1. עקוב אחר ההוראות להוספת Firebase לפרויקט C++ שלך .
  2. ממשק C++ לאנדרואיד.
    • תלות מדורגת. הוסף את הדברים הבאים למודול שלך (ברמת האפליקציה) לקובץ Gradle (בדרך כלל app/build.gradle ):
              android.defaultConfig.externalNativeBuild.cmake {
                arguments "-DFIREBASE_CPP_SDK_DIR=$gradle.firebase_cpp_sdk_dir"
              }
      
              apply from: "$gradle.firebase_cpp_sdk_dir/Android/firebase_dependencies.gradle"
              firebaseCpp.dependencies {
                // earlier entries
                auth
                firestore
              }
              
    • תלות בינארית. באופן דומה, הדרך המומלצת לקבל את התלות הבינארית היא להוסיף את הדברים הבאים לקובץ CMakeLists.txt שלך:
              add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL)
              set(firebase_libs firebase_auth firebase_firestore firebase_app)
              # Replace the target name below with the actual name of your target,
              # for example, "native-lib".
              target_link_libraries(${YOUR_TARGET_NAME_HERE} "${firebase_libs}")
              
  3. כדי להגדיר אינטגרציה של שולחן העבודה , ראה הוסף Firebase לפרויקט C++ שלך .
אַחְדוּת
  1. עקוב אחר ההוראות להוספת Firebase לפרויקט Unity שלך .
  2. השתמש בממשק Unity כדי להגדיר את הפרויקט שלך כדי להקטין את הבנייה של Android.
  3. עליך לצמצם את המבנה כדי להימנע מההודעה Error while merging dex archives .

    • ניתן למצוא את האפשרות בהגדרות נגן > אנדרואיד > הגדרות פרסום > צמצום .
    • האפשרויות עשויות להיות שונות בגרסאות שונות של Unity, לכן עיין בתיעוד הרשמי של Unity ובמדריך ניפוי הבאגים של Firebase Unity Build .
    • אם, לאחר הפעלת הקטנה, מספר השיטות שהפניה אליהן עדיין חורג מהמגבלה, אפשרות נוספת היא להפעיל multidex ב:
      • mainTemplate.gradle אם תבנית מדרוג מותאמת אישית תחת הגדרות הנגן מופעלת
      • או, קובץ build.gradle ברמת המודול, אם אתה משתמש ב-Android Studio כדי לבנות את הפרויקט המיוצא.
Node.js
  1. הוסף את Firebase Admin SDK לאפליקציה שלך:
    npm install firebase-admin --save
  2. בצע את ההוראות שלהלן כדי לאתחל את Cloud Firestore עם האישורים המתאימים בסביבה שלך.
ללכת
  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 Application לצורך אימות.
    • כדי לבצע אימות מסביבת הפיתוח שלך, הגדר את משתנה הסביבה 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 Application לצורך אימות.
    • כדי לבצע אימות מסביבת הפיתוח שלך, הגדר את משתנה הסביבה GOOGLE_APPLICATION_CREDENTIALS כך שיצביע על קובץ מפתח של חשבון שירות JSON. אתה יכול ליצור קובץ מפתח בדף האישורים של מסוף API .
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • בסביבת הייצור שלך, אינך צריך לבצע אימות אם אתה מפעיל את היישום שלך ב-App Engine או Compute Engine, באמצעות אותו פרויקט שבו אתה משתמש עבור Cloud Firestore. אחרת, הגדר חשבון שירות .
  2. הוסף את ספריית Cloud Firestore C# לאפליקציה שלך בקובץ .csproj שלך:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  3. הוסף את הדברים הבאים לקובץ Program.cs שלך:
    using Google.Cloud.Firestore;
אוֹדֶם
  1. ספריות לקוח שרת Cloud Firestore (Java, Node.js, Python, Go, PHP, C# ו-Ruby) משתמשות באישורי ברירת המחדל של Google Application לצורך אימות.
    • כדי לבצע אימות מסביבת הפיתוח שלך, הגדר את משתנה הסביבה 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. מהשורש של ספריית הפרויקט המקומית שלך, הפעל firebase emulators:start .
  3. ביצוע שיחות מקוד אב הטיפוס של האפליקציה שלך באמצעות SDK של פלטפורמת Cloud Firestore כרגיל.

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

אתחול Cloud Firestore

אתחול מופע של 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);

החלף את FIREBASE_CONFIGURATION ב- firebaseConfig של אפליקציית האינטרנט שלך.

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

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

החלף את FIREBASE_CONFIGURATION ב- firebaseConfig של אפליקציית האינטרנט שלך.

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

מָהִיר
הערה: מוצר זה אינו זמין ביעדי watchOS ו-App Clip.
import FirebaseCore
import FirebaseFirestore
FirebaseApp.configure()

let db = Firestore.firestore()
Objective-C
הערה: מוצר זה אינו זמין ביעדי watchOS ו-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;
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 & admin > חשבונות שירות במסוף 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();
    
  • פִּיתוֹן
    ה-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 & admin > חשבונות שירות במסוף 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 & admin > חשבונות שירות במסוף 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 .
    • אתחול בפונקציות ענן
      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 & admin > חשבונות שירות במסוף 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();
      
    ללכת
    ה-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 & admin > חשבונות שירות במסוף 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);
        }
    }
    אַחְדוּת
    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);
    אוֹדֶם
    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 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);
    });
    מָהִיר
    הערה: מוצר זה אינו זמין ביעדי watchOS ו-App Clip.
    // 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 ו-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}'));
    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());
    פִּיתוֹן
    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
    });
    ללכת
    _, _, 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);
    אַחְדוּת
    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);
    אוֹדֶם
    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 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);
    });
    מָהִיר
    הערה: מוצר זה אינו זמין ביעדי watchOS ו-App Clip.
    // 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 ו-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}'));
    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());
    פִּיתוֹן
    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
    });
    ללכת
    _, _, 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);
    אַחְדוּת
    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);
    אוֹדֶם
    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."

    קרא נתונים

    השתמש במציג הנתונים במסוף Firebase כדי לוודא במהירות שהוספת נתונים ל-Cloud Firestore.

    ניתן גם להשתמש בשיטת "קבל" כדי לאחזר את כל האוסף.

    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()}`);
        });
    });
    מָהִיר
    הערה: מוצר זה אינו זמין ביעדי watchOS ו-App Clip.
    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 ו-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()}");
      }
    });
    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"));
    }
    פִּיתוֹן
    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());
    });
    ללכת
    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);
    אַחְדוּת
    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();
    }
    אוֹדֶם
    users_ref = firestore.col collection_path
    users_ref.get do |user|
      puts "#{user.document_id} data: #{user.data}."
    end

    אבטח את הנתונים שלך

    אם אתה משתמש באינטרנט, ב-Android או ב-SDK של פלטפורמות Apple, השתמש באימות Firebase ובכללי האבטחה של Cloud Firestore כדי לאבטח את הנתונים שלך ב-Cloud Firestore.

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

    נדרש אישור

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

    מצב נעול

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

    מצב מבחן

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

    לפני שתפרוס את אפליקציית האינטרנט, האנדרואיד או iOS שלך לייצור, בצע גם צעדים כדי להבטיח שרק לקוחות האפליקציה שלך יוכלו לגשת לנתוני Cloud Firestore שלך. עיין בתיעוד App Check .

    אם אתה משתמש באחת מ-SDK של השרת, השתמש בניהול זהות וגישה (IAM) כדי לאבטח את הנתונים שלך ב-Cloud Firestore.

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

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

    אינטרנט
    iOS+
    דְמוּי אָדָם

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

    הצעדים הבאים

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