תחילת העבודה עם מהדורת Firestore Standard

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

‫Cloud Firestore תומך בערכות SDK לנייד או לאינטרנט ובספריות לקוח של השרת:

  • ‫Cloud Firestore תומך בערכות SDK ל-Android, ל-iOS, לאינטרנט ועוד. בשילוב עם Cloud Firestore Security Rules ו-Firebase Authentication, ערכות ה-SDK לנייד ולאינטרנט תומכות בארכיטקטורות של אפליקציות ללא שרת (serverless), שבהן הלקוחות מתחברים ישירות למסד הנתונים של Cloud Firestore.

  • ב-Cloud Firestore יש תמיכה בספריות לקוח של שרת ל-C#‎,‏ Go,‏ Java,‏ Node.js,‏ PHP,‏ Python ו-Ruby. אתם יכולים להשתמש בספריות הלקוח האלה כדי להגדיר סביבות שרת עם הרשאות וגישה מלאה למסד הנתונים. מידע נוסף על הספריות האלה זמין במאמר מדריך למתחילים בנושא ספריות לקוח של שרת.

כדי לקבל עזרה מ-AI, מעתיקים את ההנחיה שלמטה ומדביקים אותה בסוכן ה-AI לתכנות (כמו Gemini ב-Android Studio,‏ Antigravity,‏ Claude Code,‏ Codex ו-Cursor). אתם יכולים להתאים אישית את ההנחיה ולשפר את הסוכן. מידע מפורט על ההתקנה זמין במאמר סקילים אג'נטיים ב-Firebase.

Help me use Firebase in my app.
1. Make sure that **Firebase agent skills** are installed and updated. For Claude Code, Codex, or Cursor agents, help me install the Firebase plugin. For other agents, run `npx skills add firebase/agent-skills`. Always try to use **Firebase agent skills** for Firebase-related tasks.
2. Help me set up and use Firebase for the backend of my app. Set up Firestore database in **Standard edition**. Help me to choose the best location for my database instance.

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

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

  2. בחלונית שמימין, עוברים אל Databases & Storage > Firestore.

  3. לוחצים על Create database.

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

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

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

    מצב בדיקה

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

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

    מצב ייצור

    דוחה את כל פעולות הקריאה והכתיבה מלקוחות בנייד ובאינטרנט. שרתי האפליקציות המאומתים (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 לכל מסד נתונים.

  6. לוחצים על יצירה.

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

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

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

Web

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

Web

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

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

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

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

    כשמשתמשים בעץ המוצר (BoM) של Firebase ל-Android, האפליקציה תמיד משתמשת בגרסאות תואמות של ספריות 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:27.0.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, אפשר לכלול את ה-framework שעבר הידור מראש.

    נכון לעכשיו, ה-SDK של Firestore ל-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_sdk_version.rb של firebase_core. אם אתם לא משתמשים ב<b>גרסה העדכנית</b> של firebase_core, חפשו את הקובץ הזה במטמון של חבילת Pub המקומית (בדרך כלל ~/.pub-cache).

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

    gem install cocoapods

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

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:
              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.
  2. משתמשים בממשק של Unity כדי להגדיר את הפרויקט כך שיקטין את גרסאות ה-build ל-Android.
  3. כדי למנוע את הצגת ההודעה Error while merging dex archives, צריך למזער את ה-build.

    • האפשרות הזו נמצאת ב-Player Settings > Android > Publishing Settings > Minify.
    • יכול להיות שהאפשרויות יהיו שונות בגרסאות שונות של Unity, לכן כדאי לעיין במסמכי התיעוד הרשמיים של Unity ובמדריך לניפוי באגים ב-Firebase Unity Build.
    • אם אחרי הפעלת ההקטנה, מספר השיטות שאליהן מפנים עדיין חורג מהמגבלה, אפשרות נוספת היא להפעיל את multidex ב:
      • mainTemplate.gradle אם האפשרות Custom Gradle Template (תבנית Gradle בהתאמה אישית) מופעלת בקטע Player Settings (הגדרות הנגן)
      • או בקובץ build.gradle ברמת המודול, אם אתם משתמשים ב-Android Studio כדי ליצור את הפרויקט שייצאתם.

(אופציונלי) יצירת אב טיפוס ובדיקה באמצעות 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 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 ו-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

// 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;
C++‎
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().
App::Create();
Firestore* db = Firestore::GetInstance();
Unity
using Firebase.Firestore;
using Firebase.Extensions;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;

הוספת נתונים

ב-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 ו-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

// Create a new user with a first and last name
val user = hashMapOf(
    "first" to "Ada",
    "last" to "Lovelace",
    "born" to 1815,
)

// Add a new document with a generated ID
db.collection("users")
    .add(user)
    .addOnSuccessListener { documentReference ->
        Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "Error adding document", e)
    }

Java

// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("first", "Ada");
user.put("last", "Lovelace");
user.put("born", 1815);

// Add a new document with a generated ID
db.collection("users")
        .add(user)
        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error adding document", e);
            }
        });

Dart

// Create a new user with a first and last name
final user = <String, dynamic>{
  "first": "Ada",
  "last": "Lovelace",
  "born": 1815
};

// Add a new document with a generated ID
db.collection("users").add(user).then((DocumentReference doc) =>
    print('DocumentSnapshot added with ID: ${doc.id}'));
C++‎
// Add a new document with a generated ID
Future<DocumentReference> user_ref =
    db->Collection("users").Add({{"first", FieldValue::String("Ada")},
                                 {"last", FieldValue::String("Lovelace")},
                                 {"born", FieldValue::Integer(1815)}});

user_ref.OnCompletion([](const Future<DocumentReference>& future) {
  if (future.error() == Error::kErrorOk) {
    std::cout << "DocumentSnapshot added with ID: " << future.result()->id()
              << std::endl;
  } else {
    std::cout << "Error adding document: " << future.error_message() << std::endl;
  }
});
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.");
});

עכשיו צריך להוסיף עוד מסמך לאוסף 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 ו-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

// Create a new user with a first, middle, and last name
val user = hashMapOf(
    "first" to "Alan",
    "middle" to "Mathison",
    "last" to "Turing",
    "born" to 1912,
)

// Add a new document with a generated ID
db.collection("users")
    .add(user)
    .addOnSuccessListener { documentReference ->
        Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "Error adding document", e)
    }

Java

// Create a new user with a first, middle, and last name
Map<String, Object> user = new HashMap<>();
user.put("first", "Alan");
user.put("middle", "Mathison");
user.put("last", "Turing");
user.put("born", 1912);

// Add a new document with a generated ID
db.collection("users")
        .add(user)
        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error adding document", e);
            }
        });

Dart

// Create a new user with a first and last name
final user = <String, dynamic>{
  "first": "Alan",
  "middle": "Mathison",
  "last": "Turing",
  "born": 1912
};

// Add a new document with a generated ID
db.collection("users").add(user).then((DocumentReference doc) =>
    print('DocumentSnapshot added with ID: ${doc.id}'));
C++‎
db->Collection("users")
    .Add({{"first", FieldValue::String("Alan")},
          {"middle", FieldValue::String("Mathison")},
          {"last", FieldValue::String("Turing")},
          {"born", FieldValue::Integer(1912)}})
    .OnCompletion([](const Future<DocumentReference>& future) {
      if (future.error() == Error::kErrorOk) {
        std::cout << "DocumentSnapshot added with ID: "
                  << future.result()->id() << std::endl;
      } else {
        std::cout << "Error adding document: " << future.error_message()
                  << std::endl;
      }
    });
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.");
});

קריאת נתונים

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

אפשר גם להשתמש ב-method‏ "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 ו-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

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

Java

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

Dart

await db.collection("users").get().then((event) {
  for (var doc in event.docs) {
    print("${doc.id} => ${doc.data()}");
  }
});
C++‎
Future<QuerySnapshot> users = db->Collection("users").Get();
users.OnCompletion([](const Future<QuerySnapshot>& future) {
  if (future.error() == Error::kErrorOk) {
    for (const DocumentSnapshot& document : future.result()->documents()) {
      std::cout << document << std::endl;
    }
  } else {
    std::cout << "Error getting documents: " << future.error_message()
              << std::endl;
  }
});
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.");
});

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

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

ריכזנו כאן כמה קבוצות כללים בסיסיות שיעזרו לכם להתחיל. אפשר לשנות את כללי האבטחה במסוף Firebase, בקטע Databases & Storage (מסדי נתונים ואחסון) > Firestore > הכרטיסייה Rules (כללים).

נדרש אימות

// 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. לעיון במאמרי העזרה של App Check

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

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

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

אינטרנט
iOS+‎
Android

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

השלבים הבאים

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