เริ่มต้นใช้งาน Firestore รุ่นมาตรฐาน

คู่มือเริ่มใช้งานฉบับย่อนี้จะแสดงวิธีตั้งค่า 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) คุณสามารถปรับแต่งพรอมต์และปรับปรุงซ้ำๆ กับ Agent ได้ ดูข้อมูลการติดตั้งโดยละเอียดได้ที่ทักษะเอเจนต์ 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 แล้วคลิกเพิ่มโปรเจ็กต์ จากนั้นทำตามวิธีการบนหน้าจอเพื่อสร้างโปรเจ็กต์ Firebase หรือเพิ่มบริการ Firebase ลงในโปรเจ็กต์ Google Cloud ที่มีอยู่

  2. ในแผงด้านซ้าย ให้ไปที่ฐานข้อมูลและพื้นที่เก็บข้อมูล > Firestore

  3. คลิกสร้างฐานข้อมูล

  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 ด้วย

ตั้งค่าสภาพแวดล้อมในการพัฒนาซอฟต์แวร์

เพิ่มทรัพยากร Dependency และไลบรารีของไคลเอ็นต์ที่จำเป็นลงในแอป

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>
    นอกจากนี้ SDK ของ Cloud Firestore ยังพร้อมใช้งานเป็นแพ็กเกจ 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 เพื่อติดตั้งและจัดการทรัพยากร Dependency ของ Firebase

  1. ใน Xcode ขณะที่โปรเจ็กต์แอปเปิดอยู่ ให้ไปที่ไฟล์ > แพ็กเกจ Swift > เพิ่มทรัพยากร Dependency ของแพ็กเกจ
  2. เมื่อได้รับข้อความแจ้ง ให้เพิ่มที่เก็บ SDK ของ Firebase สำหรับแพลตฟอร์ม Apple ดังนี้
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. เลือกไลบรารี Firestore
  5. เมื่อเสร็จแล้ว Xcode จะเริ่มแก้ไขและดาวน์โหลดทรัพยากร Dependency ในเบื้องหลังโดยอัตโนมัติ
Android
  1. ทำตามวิธีการเพื่อเพิ่ม Firebase ลงในแอป Android
  2. เมื่อใช้ Firebase Android BoM ให้ประกาศทรัพยากร Dependency สำหรับไลบรารี 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")
    }

    การใช้ Firebase Android BoM จะทำให้แอปใช้ไลบรารี Firebase Android เวอร์ชันที่เข้ากันได้อยู่เสมอ

    (ทางเลือก) ประกาศทรัพยากร Dependency ของไลบรารี Firebase โดยไม่ใช้ BoM

    หากเลือกที่จะไม่ใช้ Firebase BoM คุณต้องระบุไลบรารี Firebase แต่ละเวอร์ชันในบรรทัดทรัพยากร Dependency

    โปรดทราบว่าหากคุณใช้ไลบรารี 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. จากรูทของโปรเจ็กต์ Flutter ให้เรียกใช้คําสั่งต่อไปนี้เพื่อติดตั้งปลั๊กอิน
    flutter pub add cloud_firestore
  3. เมื่อเสร็จแล้ว ให้สร้างแอปพลิเคชัน Flutter อีกครั้งโดยทำดังนี้
    flutter run
  4. ไม่บังคับ: ปรับปรุงเวลาในการสร้าง iOS และ macOS โดยรวมเฟรมเวิร์กที่คอมไพล์ไว้ล่วงหน้า

    ปัจจุบัน Firestore SDK สำหรับ iOS ขึ้นอยู่กับโค้ดที่อาจใช้เวลาสร้างใน Xcode นานกว่า 5 นาที หากต้องการลดเวลาในการสร้างอย่างมาก คุณสามารถใช้เวอร์ชันที่คอมไพล์ล่วงหน้าได้โดยเพิ่มบรรทัดนี้ลงในบล็อก 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 หากคุณไม่ได้ใช้ firebase_core เวอร์ชันล่าสุด ให้มองหาไฟล์นี้ในแคชแพ็กเกจ Pub ในเครื่อง (โดยปกติคือ ~/.pub-cache)

    นอกจากนี้ โปรดตรวจสอบว่าคุณได้อัปเกรด CocoaPods เป็น 1.9.1 ขึ้นไปแล้ว

    gem install cocoapods

    ดูข้อมูลเพิ่มเติมได้ที่ปัญหาใน GitHub

C++
  1. ทำตามวิธีการเพื่อเพิ่ม Firebase ลงในโปรเจ็กต์ C++
  2. อินเทอร์เฟซ C++ สำหรับ Android
    • ทรัพยากร Dependency ของ 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
              }
              
    • ทรัพยากร Dependency แบบไบนารี ในทำนองเดียวกัน วิธีที่แนะนำในการรับทรัพยากร Dependency แบบไบนารีคือการเพิ่มโค้ดต่อไปนี้ลงในไฟล์ 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 เพื่อกำหนดค่าโปรเจ็กต์ให้ลดขนาดบิลด์ Android
  3. คุณต้องลดขนาดบิลด์เพื่อหลีกเลี่ยงข้อความ Error while merging dex archives

    • ตัวเลือกนี้จะอยู่ใน Player Settings > Android > Publishing Settings > Minify
    • ตัวเลือกอาจแตกต่างกันไปใน Unity เวอร์ชันต่างๆ ดังนั้นโปรดดูเอกสารประกอบอย่างเป็นทางการของ Unity และคู่มือการแก้ไขข้อบกพร่องของบิลด์ Firebase Unity
    • หากเปิดใช้การลดขนาดแล้ว แต่จำนวนเมธอดที่อ้างอิงยังคงเกินขีดจำกัด อีกทางเลือกหนึ่งคือเปิดใช้ multidex ใน
      • mainTemplate.gradle หากเปิดใช้ Custom Gradle Template ในส่วน 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.");
});

อ่านข้อมูล

ใช้โปรแกรมดูข้อมูลในคอนโซล 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 และ 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 ในแท็บฐานข้อมูลและพื้นที่เก็บข้อมูล > 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 ได้ ดูเอกสารประกอบของ App Check

หากคุณใช้ SDK ของเซิร์ฟเวอร์รายการใดรายการหนึ่ง ให้ใช้ Identity and Access Management (IAM) เพื่อรักษาความปลอดภัยของข้อมูลใน Cloud Firestore

ดูวิดีโอแนะนำ

ดูคำแนะนำโดยละเอียดเกี่ยวกับการเริ่มต้นใช้งานไลบรารีของไคลเอ็นต์มือถือ Cloud Firestore ได้จากวิดีโอแนะนำรายการใดรายการหนึ่งต่อไปนี้

เว็บ
iOS+
Android

ดูวิดีโอเพิ่มเติมได้ในช่อง YouTube ของ Firebase

ขั้นตอนถัดไป

เพิ่มพูนความรู้ด้วยหัวข้อต่อไปนี้

  • Codelabs - ดูวิธีใช้ Cloud Firestore ในแอปจริงโดยทำตาม Codelab สำหรับ Android, iOS หรือเว็บ
  • โมเดลข้อมูล - ดูข้อมูลเพิ่มเติมเกี่ยวกับวิธีจัดโครงสร้างข้อมูลใน Cloud Firestore รวมถึงข้อมูลแบบลำดับชั้นและคอลเล็กชันย่อย
  • เพิ่มข้อมูล - ดูข้อมูลเพิ่มเติมเกี่ยวกับการสร้างและอัปเดตข้อมูลใน Cloud Firestore
  • รับข้อมูล - ดูข้อมูลเพิ่มเติมเกี่ยวกับวิธีดึงข้อมูล
  • ทำการค้นหาแบบง่ายและแบบผสม - ดูวิธีเรียกใช้การค้นหาแบบง่ายและแบบผสม
  • จัดลำดับและจำกัดการค้นหา ดูวิธีจัดลำดับและจำกัดข้อมูลที่แสดงผลจากการค้นหา
  • ทักษะเอเจนต์ Firebase - ดูวิธีปรับปรุงเครื่องมือสำหรับนักพัฒนาซอฟต์แวร์ AI เพื่อทำงานได้อย่างมีประสิทธิภาพมากขึ้นและใช้แนวทางปฏิบัติแนะนำของ Cloud Firestore (เช่น การเขียน Cloud Firestore Security Rules)