การเริ่มต้นอย่างรวดเร็วนี้แสดงให้เห็นวิธีตั้งค่า Cloud Firestore เพิ่มข้อมูล แล้วดู ข้อมูลที่คุณเพิ่งเพิ่มในคอนโซล Firebase
Cloud Firestore รองรับ SDK บนอุปกรณ์เคลื่อนที่หรือเว็บ และไลบรารีไคลเอ็นต์ของเซิร์ฟเวอร์
Cloud Firestore รองรับ SDK สำหรับ Android, iOS, เว็บ และอื่นๆ เมื่อใช้ร่วมกับ Cloud Firestore Security Rules และ Firebase Authentication SDK สำหรับอุปกรณ์เคลื่อนที่และเว็บจะรองรับ สถาปัตยกรรมแอปแบบไร้เซิร์ฟเวอร์ที่ไคลเอ็นต์เชื่อมต่อโดยตรงกับฐานข้อมูล Cloud Firestore
Cloud Firestore รองรับไลบรารีของไคลเอ็นต์เซิร์ฟเวอร์สำหรับ C#, Go, Java, Node.js, PHP, Python และ Ruby ใช้ไลบรารีของไคลเอ็นต์เหล่านี้เพื่อตั้งค่าสภาพแวดล้อมของเซิร์ฟเวอร์ที่มีสิทธิ์ พร้อมสิทธิ์เข้าถึงฐานข้อมูลอย่างเต็มรูปแบบ ดูข้อมูลเพิ่มเติมเกี่ยวกับไลบรารีเหล่านี้ได้ ในการเริ่มต้นอย่างรวดเร็วสำหรับไลบรารีของไคลเอ็นต์เซิร์ฟเวอร์
สร้างฐานข้อมูล Cloud Firestore
หากยังไม่ได้สร้างโปรเจ็กต์ Firebase ให้สร้างในFirebaseคอนโซลโดยคลิกเพิ่มโปรเจ็กต์ แล้วทำตามวิธีการบนหน้าจอเพื่อสร้างโปรเจ็กต์ Firebase หรือเพิ่มบริการ Firebase ลงในGoogle Cloudโปรเจ็กต์ที่มีอยู่
เปิดโปรเจ็กต์ในFirebaseคอนโซล ในแผงด้านซ้าย ให้ขยาย สร้าง แล้วเลือก ฐานข้อมูล Firestore
คลิกสร้างฐานข้อมูล
เลือกตำแหน่งสำหรับฐานข้อมูล
หากเลือกตำแหน่งไม่ได้ แสดงว่าระบบได้ตั้งค่า "ตำแหน่งสำหรับทรัพยากร Google Cloud เริ่มต้น" ของโปรเจ็กต์ไว้แล้ว ทรัพยากรบางอย่างของโปรเจ็กต์ (เช่น อินสแตนซ์เริ่มต้น Cloud Firestore) มีการอิงตามตำแหน่งร่วมกัน และ สามารถตั้งค่าตำแหน่งได้ทั้งในระหว่างการสร้างโปรเจ็กต์หรือเมื่อตั้งค่า บริการอื่นที่ใช้การอิงตามตำแหน่งนี้ร่วมกัน
เลือกโหมดเริ่มต้นสำหรับ 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 ใช้งานได้สำหรับฐานข้อมูลแต่ละรายการ
คลิกสร้าง
เมื่อเปิดใช้ Cloud Firestore ระบบจะเปิดใช้ API ใน Cloud API Manager ด้วย
ตั้งค่าสภาพแวดล้อมในการพัฒนา
เพิ่มทรัพยากร Dependency และไลบรารีของไคลเอ็นต์ที่จำเป็นลงในแอป
Web
- ทําตามวิธีการเพื่อ เพิ่ม Firebase ลงในเว็บแอป
-
Cloud Firestore SDK พร้อมใช้งานเป็นแพ็กเกจ npm
คุณจะต้องนำเข้าทั้ง Firebase และ Cloud Firestorenpm install firebase@12.8.0 --save
import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore";
Web
- ทําตามวิธีการเพื่อ เพิ่ม Firebase ลงในเว็บแอป
- เพิ่มไลบรารี Firebase และ Cloud Firestore ลงในแอป
Cloud Firestore SDK ยังมีให้บริการเป็นแพ็กเกจ npm ด้วย<script src="https://www.gstatic.com/firebasejs/12.8.0/firebase-app-compat.js"></script> <script src="https://www.gstatic.com/firebasejs/12.8.0/firebase-firestore-compat.js"></script>
คุณจะต้องกำหนดให้ใช้ทั้ง Firebase และ Cloud Firestore ด้วยตนเองnpm install firebase@12.8.0 --save
import firebase from "firebase/compat/app"; // Required for side-effects import "firebase/firestore";
iOS+
ทําตามวิธีการเพื่อ เพิ่ม Firebase ลงในแอป Apple
ใช้ Swift Package Manager เพื่อติดตั้งและจัดการทรัพยากร Dependency ของ Firebase
- เปิดโปรเจ็กต์แอปใน Xcode แล้วไปที่File > Swift Packages > Add Package Dependency
- เมื่อได้รับข้อความแจ้ง ให้เพิ่มที่เก็บ Firebase Apple Platforms SDK ดังนี้
- เลือกไลบรารี Firestore
- เมื่อเสร็จแล้ว Xcode จะเริ่มจับคู่ข้อมูลและดาวน์โหลดทรัพยากร Dependency ในเบื้องหลังโดยอัตโนมัติ
https://github.com/firebase/firebase-ios-sdk
Android
- ทําตามวิธีการเพื่อ เพิ่ม Firebase ลงในแอป Android
- ใช้
BoM ของ Firebase Android
ประกาศทรัพยากร 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:34.8.0")) // Declare the dependency for the Cloud Firestore library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-firestore") }
การใช้ 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:26.1.0") }
หากกำลังมองหาโมดูลไลบรารีเฉพาะของ Kotlin ตั้งแต่รุ่นเดือนตุลาคม 2023 เป็นต้นไป ทั้งนักพัฒนาแอป Kotlin และ Java จะใช้โมดูลไลบรารีหลักได้ (ดูรายละเอียดได้ที่คำถามที่พบบ่อยเกี่ยวกับโครงการนี้)
Dart
- หากยังไม่ได้ทำ ให้กำหนดค่าและ เริ่มต้น Firebase ในแอป Flutter
- จากรูทของโปรเจ็กต์ Flutter ให้เรียกใช้คำสั่งต่อไปนี้เพื่อ
ติดตั้งปลั๊กอิน
flutter pub add cloud_firestore
- เมื่อเสร็จแล้ว ให้สร้างแอปพลิเคชัน Flutter ใหม่โดยทำดังนี้
flutter run
- ไม่บังคับ: ปรับปรุงเวลาในการสร้าง iOS และ macOS โดยรวม
เฟรมเวิร์กที่คอมไพล์ล่วงหน้า
ปัจจุบัน Firestore SDK สำหรับ iOS ขึ้นอยู่กับโค้ดที่อาจใช้เวลาสร้างใน Xcode นานกว่า 5 นาที หากต้องการลดเวลาบิลด์ลงอย่างมาก คุณสามารถใช้เวอร์ชันที่คอมไพล์ล่วงหน้าได้โดยการเพิ่มบรรทัดนี้ลงในบล็อก
target 'Runner' doใน Podfiletarget '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_corefirebase_sdk_version.rbหากไม่ได้ใช้firebase_coreเวอร์ชันล่าสุด ให้ค้นหาไฟล์นี้ในแคชแพ็กเกจ Pub ในเครื่อง (โดยปกติคือ~/.pub-cache)นอกจากนี้ โปรดตรวจสอบว่าคุณได้อัปเกรด CocoaPods เป็น 1.9.1 ขึ้นไปแล้ว แล้ว
gem install cocoapods
ดูข้อมูลเพิ่มเติมได้ที่ปัญหา ใน GitHub
C++
- ทําตามวิธีการเพื่อ เพิ่ม Firebase ลงในโปรเจ็กต์ C++
- อินเทอร์เฟซ 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.txtadd_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}")
- หากต้องการตั้งค่าการผสานรวมเดสก์ท็อป โปรดดูเพิ่ม Firebase ลงในโปรเจ็กต์ C++
Unity
- ทําตามวิธีการเพื่อเพิ่ม Firebase ลงในโปรเจ็กต์ Unity
- ใช้อินเทอร์เฟซ Unity เพื่อกำหนดค่าโปรเจ็กต์ให้ลดขนาดบิลด์ Android
- คุณดูตัวเลือกนี้ได้ในการตั้งค่าเพลเยอร์ > Android > การตั้งค่าการเผยแพร่ > ลดขนาด
- ตัวเลือกอาจแตกต่างกันใน Unity เวอร์ชันต่างๆ ดังนั้นโปรดดูเอกสารประกอบอย่างเป็นทางการของ Unity และคำแนะนำในการแก้ไขข้อบกพร่องในการสร้าง Firebase Unity
-
หากหลังจากเปิดใช้การลดขนาดแล้ว จำนวนเมธอดที่อ้างอิงยังคง
เกินขีดจำกัด อีกตัวเลือกหนึ่งคือการเปิดใช้
multidexใน-
mainTemplate.gradleหากเปิดใช้ Custom Gradle Template ในส่วนPlayer Settings -
หรือไฟล์
build.gradleระดับโมดูล หากคุณใช้ Android Studio เพื่อสร้างโปรเจ็กต์ที่ส่งออก
-
คุณต้องย่อขนาดบิลด์เพื่อหลีกเลี่ยงข้อความ Error while merging dex archives
(ไม่บังคับ) สร้างต้นแบบและทดสอบด้วย Firebase Local Emulator Suite
สำหรับนักพัฒนาแอปบนอุปกรณ์เคลื่อนที่ ก่อนที่จะพูดถึงวิธีที่แอปเขียนและอ่านข้อมูล จาก Cloud Firestore มาทำความรู้จักชุดเครื่องมือที่คุณใช้ สร้างต้นแบบและทดสอบฟังก์ชันการทำงานของ Cloud Firestore กันก่อน Firebase Local Emulator Suite หากคุณกำลังทดลองใช้โมเดลข้อมูลต่างๆ เพิ่มประสิทธิภาพกฎความปลอดภัย หรือพยายามหาวิธีที่คุ้มค่าที่สุด ในการโต้ตอบกับแบ็กเอนด์ การทำงานในเครื่องโดยไม่ต้องติดตั้งใช้งาน บริการที่ใช้งานจริงอาจเป็นไอเดียที่ดี
Cloud Firestoreโปรแกรมจำลองเป็นส่วนหนึ่งของ Local Emulator Suite ซึ่งช่วยให้แอปโต้ตอบกับเนื้อหาและกำหนดค่าฐานข้อมูลจำลอง รวมถึงทรัพยากรโปรเจ็กต์จำลอง (ฟังก์ชัน ฐานข้อมูลอื่นๆ และกฎการรักษาความปลอดภัย) ได้ด้วย (ไม่บังคับ)
การใช้โปรแกรมจำลอง Cloud Firestore มีขั้นตอนเพียงไม่กี่ขั้นตอนดังนี้
- การเพิ่มบรรทัดโค้ดลงในการกำหนดค่าการทดสอบของแอปเพื่อเชื่อมต่อกับโปรแกรมจำลอง
- จากรูทของไดเรกทอรีโปรเจ็กต์ในเครื่อง ให้เรียกใช้
firebase emulators:start - ทำการเรียกจากโค้ดต้นแบบของแอปโดยใช้ Cloud Firestore SDK ของแพลตฟอร์ม ตามปกติ
มีคำแนะนำแบบทีละขั้นตอนโดยละเอียดเกี่ยวกับ Cloud Firestore และ Cloud Functions นอกจากนี้ คุณควรอ่านLocal Emulator Suiteข้อมูลเบื้องต้นด้วย
เริ่มต้น Cloud Firestore
เริ่มต้นอินสแตนซ์ของ Cloud Firestore
Web
import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore"; // TODO: Replace the following with your app's Firebase project configuration // See: https://support.google.com/firebase/answer/7015592 const firebaseConfig = { FIREBASE_CONFIGURATION }; // Initialize Firebase const app = initializeApp(firebaseConfig); // Initialize Cloud Firestore and get a reference to the service const db = getFirestore(app);
แทนที่ FIREBASE_CONFIGURATION ด้วย firebaseConfig ของเว็บแอป
หากต้องการคงข้อมูลไว้เมื่ออุปกรณ์ขาดการเชื่อมต่อ โปรดดูเอกสารประกอบเปิดใช้ข้อมูลแบบออฟไลน์
Web
import firebase from "firebase/app"; import "firebase/firestore"; // TODO: Replace the following with your app's Firebase project configuration // See: https://support.google.com/firebase/answer/7015592 const firebaseConfig = { FIREBASE_CONFIGURATION }; // Initialize Firebase firebase.initializeApp(firebaseConfig); // Initialize Cloud Firestore and get a reference to the service const db = firebase.firestore();
แทนที่ FIREBASE_CONFIGURATION ด้วย firebaseConfig ของเว็บแอป
หากต้องการคงข้อมูลไว้เมื่ออุปกรณ์ขาดการเชื่อมต่อ โปรดดูเอกสารประกอบเปิดใช้ข้อมูลแบบออฟไลน์
Swift
import FirebaseCore import FirebaseFirestore
FirebaseApp.configure() let db = Firestore.firestore()
Objective-C
@import FirebaseCore; @import FirebaseFirestore; // Use Firebase library to configure APIs [FIRApp configure];
FIRFirestore *defaultFirestore = [FIRFirestore firestore];
Kotlin
// Access a Cloud Firestore instance from your Activityval db = Firebase.firestore
Java
// Access a Cloud Firestore instance from your ActivityFirebaseFirestore 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
// 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
// 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
// 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
// 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
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
[[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
ต่อไปนี้คือชุดกฎพื้นฐานบางส่วนที่คุณใช้เพื่อเริ่มต้นได้ คุณสามารถแก้ไข กฎความปลอดภัยได้ในแท็บกฎของ คอนโซล
ต้องมีการตรวจสอบสิทธิ์
// 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
ขั้นตอนถัดไป
เพิ่มพูนความรู้ด้วยหัวข้อต่อไปนี้
- Codelab - เรียนรู้วิธีใช้ Cloud Firestore ในแอปจริงโดย ทำตาม Codelab สำหรับ Android, iOS หรือ เว็บ
- โมเดลข้อมูล - ดูข้อมูลเพิ่มเติมเกี่ยวกับวิธีจัดโครงสร้างข้อมูลใน Cloud Firestore รวมถึงข้อมูลลำดับชั้นและคอลเล็กชันย่อย
- เพิ่มข้อมูล — ดูข้อมูลเพิ่มเติมเกี่ยวกับการสร้างและอัปเดตข้อมูลใน Cloud Firestore
- รับข้อมูล - ดูข้อมูลเพิ่มเติมเกี่ยวกับวิธีดึงข้อมูล
- ทำการค้นหาแบบง่ายและแบบผสม - ดูวิธีเรียกใช้การค้นหาแบบง่ายและแบบผสม
- จัดเรียงและจำกัดการค้นหา ดูวิธีจัดเรียง และจำกัดข้อมูลที่การค้นหาแสดง