การเริ่มต้นอย่างรวดเร็วนี้จะแสดงวิธีตั้งค่า Cloud Firestore เพิ่มข้อมูลจากนั้นดูข้อมูลที่คุณเพิ่งเพิ่มในคอนโซล Firebase
สร้างฐานข้อมูล Cloud Firestore
สร้างโปรเจ็กต์ Firebase ใน คอนโซล Firebase คลิก เพิ่มโปรเจ็ก ต์จากนั้นทำตามคำแนะนำบนหน้าจอเพื่อสร้างโปรเจ็กต์ Firebase หรือเพิ่มบริการ Firebase ในโปรเจ็กต์ GCP ที่มีอยู่
ไปที่ส่วน Cloud Firestore ของ คอนโซล Firebase คุณจะได้รับแจ้งให้เลือกโครงการ Firebase ที่มีอยู่ ทำตามขั้นตอนการสร้างฐานข้อมูล
เลือกโหมดเริ่มต้นสำหรับกฎความปลอดภัย Cloud Firestore ของคุณ:
- โหมดทดสอบ
เหมาะสำหรับการเริ่มต้นใช้งานไลบรารีไคลเอ็นต์บนอุปกรณ์เคลื่อนที่และเว็บ แต่อนุญาตให้ทุกคนอ่านและเขียนทับข้อมูลของคุณได้ หลังจากการทดสอบโปรด ตรวจสอบส่วนการ รักษาความปลอดภัยข้อมูลของคุณ
ในการเริ่มต้นกับเว็บ iOS หรือ Android SDK ให้เลือกโหมดทดสอบ
- โหมดล็อค
ปฏิเสธการอ่านและเขียนทั้งหมดจากไคลเอนต์มือถือและเว็บ แอปพลิเคชันเซิร์ฟเวอร์ที่ได้รับการรับรองความถูกต้องของคุณ (C #, Go, Java, Node.js, PHP, Python หรือ Ruby) ยังสามารถเข้าถึงฐานข้อมูลของคุณได้
ในการเริ่มต้นกับไลบรารีไคลเอ็นต์เซิร์ฟเวอร์ C #, Go, Java, Node.js, PHP, Python หรือ Ruby ให้เลือกโหมดล็อก
เลือก ตำแหน่ง สำหรับฐานข้อมูลของคุณ
การตั้งค่าตำแหน่งนี้เป็น ตำแหน่งทรัพยากร Google Cloud Platform (GCP) เริ่มต้น ของโปรเจ็กต์ของคุณ โปรดทราบว่าตำแหน่งนี้จะใช้สำหรับบริการ GCP ในโครงการของคุณที่ต้องมีการตั้งค่าตำแหน่งโดยเฉพาะที่ เก็บข้อมูล Cloud Storage เริ่มต้นและ แอป App Engine ของคุณ (ซึ่งจำเป็นหากคุณใช้ Cloud Scheduler)
หากคุณไม่สามารถเลือกตำแหน่งได้แสดงว่าโปรเจ็กต์ของคุณมีตำแหน่งทรัพยากร GCP เริ่มต้นอยู่แล้ว มีการตั้งค่าระหว่างการสร้างโปรเจ็กต์หรือเมื่อตั้งค่าบริการอื่นที่ต้องมีการตั้งค่าสถานที่
คลิก เสร็จสิ้น
เมื่อคุณเปิดใช้งาน Cloud Firestore จะเป็นการเปิดใช้ API ใน Cloud API Manager ด้วย
ตั้งค่าสภาพแวดล้อมการพัฒนาของคุณ
เพิ่มการอ้างอิงที่จำเป็นและไลบรารีไคลเอ็นต์ลงในแอปของคุณ
เว็บ
- ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในเว็บแอปของ คุณ
- เพิ่มไลบรารี Firebase และ Cloud Firestore ลงในแอปของคุณ:
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-firestore.js"></script>
Cloud Firestore SDK ยังพร้อมใช้งานเป็นแพ็กเกจ npmnpm install firebase@8.2.9 --save
คุณจะต้องใช้ทั้ง Firebase และ Cloud Firestore ด้วยตนเองconst firebase = require("firebase"); // Required for side-effects require("firebase/firestore");
iOS
- ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในแอป iOS ของคุณ
- เพิ่ม Cloud Firestore pod ใน
Podfile
ของคุณ - บันทึกไฟล์และเรียกใช้การ
pod install
Java
- ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในแอป Android ของคุณ
- ใช้ Firebase Android BoM ประกาศการพึ่งพาไลบรารี Android ของ Cloud Firestore ใน ไฟล์ Gradle ของ โมดูล (ระดับแอป) (โดยทั่วไปคือ
app/build.gradle
)dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.6.0') // Declare the dependency for the Cloud Firestore library // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-firestore' }
เมื่อใช้ Firebase Android BoM แอปของคุณจะใช้ไลบรารี 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:22.1.1' }
โคตรลิน + KTX
- ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในแอป Android ของคุณ
- ใช้ Firebase Android BoM ประกาศการพึ่งพาไลบรารี Android ของ Cloud Firestore ใน ไฟล์ Gradle ของ โมดูล (ระดับแอป) (โดยทั่วไปคือ
app/build.gradle
)dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.6.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-ktx' }
เมื่อใช้ 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-ktx:22.1.1' }
Java
- เพิ่ม Firebase Admin SDK ลงในแอปของคุณ:
- ใช้ Gradle:
compile 'com.google.firebase:firebase-admin:7.1.0'
- ใช้ Maven:
<dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>7.1.0</version> </dependency>
- ใช้ Gradle:
- ทำตามคำแนะนำด้านล่างเพื่อเริ่มต้น Cloud Firestore ด้วยข้อมูลรับรองที่เหมาะสมในสภาพแวดล้อมของคุณ
Python
- เพิ่ม Firebase Admin SDK ลงในแอป Python:
pip install --upgrade firebase-admin
- ทำตามคำแนะนำด้านล่างเพื่อเริ่มต้น Cloud Firestore ด้วยข้อมูลรับรองที่เหมาะสมในสภาพแวดล้อมของคุณ
C ++
- ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในโปรเจ็กต์ C ++ ของ คุณ
- อินเทอร์เฟซ 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}")
- หากต้องการตั้งค่า การรวมเดสก์ท็อป โปรดดู เพิ่ม Firebase ในโปรเจ็กต์ C ++
ความสามัคคี
- ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในโปรเจ็กต์ Unity
- อินเทอร์เฟซ Unity สำหรับ Android
- เลือกไฟล์> สร้างการตั้งค่า
- เปลี่ยน 'Platform' เป็น 'Android' แล้วคลิก 'Switch Platform'
- คลิก 'การตั้งค่าผู้เล่น ... '
- ใน Unity UI หลักภายใต้ "การตั้งค่าสำหรับ Android" ให้เลือก "การตั้งค่าการเผยแพร่"
- ภายใต้ส่วน "ลดขนาด" ให้เปลี่ยนการตั้งค่าทั้งรุ่นและการแก้ปัญหาจาก "ไม่มี" เป็น "ProGuard"
เมื่อสร้างสำหรับ Android ให้เปิดใช้งาน ProGuarding เพื่อหลีกเลี่ยงขีด จำกัด Android DEX ในการทำเช่นนั้นในตัวแก้ไข Unity:
โหนด js
- เพิ่ม Firebase Admin SDK ลงในแอปของคุณ:
npm install firebase-admin --save
- ทำตามคำแนะนำด้านล่างเพื่อเริ่มต้น Cloud Firestore ด้วยข้อมูลรับรองที่เหมาะสมในสภาพแวดล้อมของคุณ
ไป
- เพิ่ม Firebase Admin SDK ลงในแอป Go ของคุณ:
go get firebase.google.com/go
- ทำตามคำแนะนำด้านล่างเพื่อเริ่มต้น Cloud Firestore ด้วยข้อมูลรับรองที่เหมาะสมในสภาพแวดล้อมของคุณ
PHP
- ไลบรารีไคลเอ็นต์เซิร์ฟเวอร์ Cloud Firestore (Java, Node.js, Python, Go, PHP, C # และ Ruby) ใช้ Google Application Default Credentials สำหรับการตรวจสอบสิทธิ์
- ในการตรวจสอบสิทธิ์จากสภาพแวดล้อมการพัฒนาของคุณให้ตั้งค่าตัวแปรสภาพแวดล้อม
GOOGLE_APPLICATION_CREDENTIALS
ให้ชี้ไปที่ไฟล์คีย์ของบัญชีบริการ JSON คุณสามารถสร้างไฟล์คีย์ได้ในหน้า API Console Credentialsexport GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- ในสภาพแวดล้อมการใช้งานจริงคุณไม่จำเป็นต้องตรวจสอบสิทธิ์หากคุณเรียกใช้แอปพลิเคชันบน App Engine หรือ Compute Engine โดยใช้โปรเจ็กต์เดียวกับที่คุณใช้สำหรับ Cloud Firestore มิฉะนั้นให้ ตั้งค่าบัญชีบริการ
- ในการตรวจสอบสิทธิ์จากสภาพแวดล้อมการพัฒนาของคุณให้ตั้งค่าตัวแปรสภาพแวดล้อม
- ติดตั้งและเปิดใช้งาน ส่วนขยาย gRPC สำหรับ PHP ซึ่งคุณจะต้องใช้ไลบรารีไคลเอนต์
- เพิ่มไลบรารี Cloud Firestore PHP ในแอปของคุณ:
composer require google/cloud-firestore
ค#
- ไลบรารีไคลเอ็นต์เซิร์ฟเวอร์ Cloud Firestore (Java, Node.js, Python, Go, PHP, C # และ Ruby) ใช้ Google Application Default Credentials สำหรับการตรวจสอบสิทธิ์
- ในการตรวจสอบสิทธิ์จากสภาพแวดล้อมการพัฒนาของคุณให้ตั้งค่าตัวแปรสภาพแวดล้อม
GOOGLE_APPLICATION_CREDENTIALS
ให้ชี้ไปที่ไฟล์คีย์ของบัญชีบริการ JSON คุณสามารถสร้างไฟล์คีย์ได้ในหน้า API Console Credentialsexport GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- ในสภาพแวดล้อมการใช้งานจริงคุณไม่จำเป็นต้องตรวจสอบสิทธิ์หากคุณเรียกใช้แอปพลิเคชันบน App Engine หรือ Compute Engine โดยใช้โปรเจ็กต์เดียวกับที่คุณใช้สำหรับ Cloud Firestore มิฉะนั้นให้ ตั้งค่าบัญชีบริการ
- ในการตรวจสอบสิทธิ์จากสภาพแวดล้อมการพัฒนาของคุณให้ตั้งค่าตัวแปรสภาพแวดล้อม
- เพิ่มไลบรารี Cloud Firestore C # ลงในแอปของคุณในไฟล์
.csproj
:<ItemGroup> <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" /> </ItemGroup>
- เพิ่มสิ่งต่อไปนี้ในไฟล์
Program.cs
ของคุณ:using Google.Cloud.Firestore;
ทับทิม
- ไลบรารีไคลเอ็นต์เซิร์ฟเวอร์ Cloud Firestore (Java, Node.js, Python, Go, PHP, C # และ Ruby) ใช้ Google Application Default Credentials สำหรับการตรวจสอบสิทธิ์
- ในการตรวจสอบสิทธิ์จากสภาพแวดล้อมการพัฒนาของคุณให้ตั้งค่าตัวแปรสภาพแวดล้อม
GOOGLE_APPLICATION_CREDENTIALS
ให้ชี้ไปที่ไฟล์คีย์ของบัญชีบริการ JSON คุณสามารถสร้างไฟล์คีย์ได้ในหน้า API Console Credentialsexport GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- ในสภาพแวดล้อมการใช้งานจริงคุณไม่จำเป็นต้องตรวจสอบสิทธิ์หากคุณเรียกใช้แอปพลิเคชันบน App Engine หรือ Compute Engine โดยใช้โปรเจ็กต์เดียวกับที่คุณใช้สำหรับ Cloud Firestore มิฉะนั้นให้ ตั้งค่าบัญชีบริการ
- ในการตรวจสอบสิทธิ์จากสภาพแวดล้อมการพัฒนาของคุณให้ตั้งค่าตัวแปรสภาพแวดล้อม
- เพิ่มไลบรารี Cloud Firestore Ruby ในแอปของคุณใน
Gemfile
:gem "google-cloud-firestore"
- ติดตั้งการอ้างอิงจาก
Gemfile
ของคุณโดยใช้:bundle install
เริ่มต้น Cloud Firestore
เริ่มต้นอินสแตนซ์ของ Cloud Firestore:
เว็บ
// Initialize Cloud Firestore through Firebase firebase.initializeApp({ apiKey: '### FIREBASE API KEY ###', authDomain: '### FIREBASE AUTH DOMAIN ###', projectId: '### CLOUD FIRESTORE PROJECT ID ###' }); var db = firebase.firestore();ค่าสำหรับ "initializeApp" สามารถพบได้ใน "firebaseConfig" ของเว็บแอปของคุณ หากต้องการคงข้อมูลไว้เมื่ออุปกรณ์ขาดการเชื่อมต่อโปรดดูเอกสาร เปิดใช้งานข้อมูลออฟไลน์
รวดเร็ว
import Firebase FirebaseApp.configure() let db = Firestore.firestore()
วัตถุประสงค์ -C
@import Firebase; // Use Firebase library to configure APIs [FIRApp configure]; FIRFirestore *defaultFirestore = [FIRFirestore firestore];
Java
// Access a Cloud Firestore instance from your Activity FirebaseFirestore db = FirebaseFirestore.getInstance();
โคตรลิน + KTX
// Access a Cloud Firestore instance from your Activity val db = Firebase.firestore
Java
Cloud Firestore SDK เริ่มต้นด้วยวิธีต่างๆขึ้นอยู่กับสภาพแวดล้อมของคุณ ด้านล่างนี้เป็นวิธีการที่พบบ่อยที่สุด สำหรับข้อมูลอ้างอิงทั้งหมดโปรดดูที่ เริ่มต้น Admin SDKimport 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> บัญชีบริการ ใน Cloud Platform Console สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ JSON จากนั้นใช้ไฟล์เพื่อเริ่มต้น SDK:
import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.firestore.Firestore; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; // Use a service account InputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json"); GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount); FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(credentials) .build(); FirebaseApp.initializeApp(options); Firestore db = FirestoreClient.getFirestore();
Python
Cloud Firestore SDK เริ่มต้นด้วยวิธีต่างๆขึ้นอยู่กับสภาพแวดล้อมของคุณ ด้านล่างนี้เป็นวิธีการที่พบบ่อยที่สุด สำหรับข้อมูลอ้างอิงทั้งหมดโปรดดูที่ เริ่มต้น Admin SDKimport 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, { 'projectId': project_id, }) db = firestore.client()
หากต้องการใช้ Firebase Admin SDK บนเซิร์ฟเวอร์ของคุณเองให้ใช้ บัญชีบริการ
ไปที่ IAM & admin> บัญชีบริการ ใน Cloud Platform Console สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ 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') firebase_admin.initialize_app(cred) db = firestore.client()
C ++
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance(). App::Create(); Firestore* db = Firestore::GetInstance();
โหนด js
Cloud Firestore SDK เริ่มต้นด้วยวิธีต่างๆขึ้นอยู่กับสภาพแวดล้อมของคุณ ด้านล่างนี้เป็นวิธีการที่พบบ่อยที่สุด สำหรับข้อมูลอ้างอิงทั้งหมดโปรดดูที่ เริ่มต้น Admin SDK- เริ่มต้นบน Cloud Functions
const admin = require('firebase-admin'); admin.initializeApp(); const db = admin.firestore();
- เริ่มต้นบน Google Cloud Platform
const admin = require('firebase-admin'); admin.initializeApp({ credential: admin.credential.applicationDefault() }); const db = admin.firestore();
- เริ่มต้นบนเซิร์ฟเวอร์ของคุณเอง
หากต้องการใช้ Firebase Admin SDK บนเซิร์ฟเวอร์ของคุณเอง (หรือสภาพแวดล้อม Node.js อื่น ๆ ) ให้ใช้ บัญชีบริการ ไปที่ IAM & admin> บัญชีบริการ ใน Cloud Platform Console สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ JSON จากนั้นใช้ไฟล์เพื่อเริ่มต้น SDK:
const admin = require('firebase-admin'); const serviceAccount = require('./path/to/serviceAccountKey.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }); const db = admin.firestore();
ไป
Cloud Firestore SDK เริ่มต้นด้วยวิธีต่างๆขึ้นอยู่กับสภาพแวดล้อมของคุณ ด้านล่างนี้เป็นวิธีการที่พบบ่อยที่สุด สำหรับข้อมูลอ้างอิงทั้งหมดโปรดดูที่ เริ่มต้น Admin SDKimport ( "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> บัญชีบริการ ใน Cloud Platform Console สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ 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
use Google\Cloud\Firestore\FirestoreClient; /** * Initialize Cloud Firestore with default project ID. * ``` * initialize(); * ``` */ function initialize() { // Create the Cloud Firestore client $db = new FirestoreClient(); printf('Created Cloud Firestore client with default project ID.' . PHP_EOL); }
ความสามัคคี
using Firebase.Firestore; using Firebase.Extensions; FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
ค#
FirestoreDb db = FirestoreDb.Create(project); Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
ทับทิม
require "google/cloud/firestore" firestore = Google::Cloud::Firestore.new project_id: project_id puts "Created Cloud Firestore client with given project ID."
เพิ่มข้อมูล
Cloud Firestore เก็บข้อมูลในเอกสารซึ่งเก็บไว้ใน Collections Cloud Firestore สร้างคอลเล็กชันและเอกสารโดยปริยายในครั้งแรกที่คุณเพิ่มข้อมูลลงในเอกสาร คุณไม่จำเป็นต้องสร้างคอลเล็กชันหรือเอกสารอย่างชัดเจน
สร้างคอลเล็กชันใหม่และเอกสารโดยใช้โค้ดตัวอย่างต่อไปนี้
เว็บ
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); });
รวดเร็ว
// Add a new document with a generated ID var ref: DocumentReference? = nil ref = db.collection("users").addDocument(data: [ "first": "Ada", "last": "Lovelace", "born": 1815 ]) { err in if let err = err { print("Error adding document: \(err)") } else { print("Document added with ID: \(ref!.documentID)") } }
วัตถุประสงค์ -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); } }];
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); } });
โคตรลิน + 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
DocumentReference docRef = db.collection("users").document("alovelace"); // Add document data with id "alovelace" using a hashmap Map<String, Object> data = new HashMap<>(); data.put("first", "Ada"); data.put("last", "Lovelace"); data.put("born", 1815); //asynchronously write data ApiFuture<WriteResult> result = docRef.set(data); // ... // result.get() blocks on response System.out.println("Update time : " + result.get().getUpdateTime());
Python
doc_ref = db.collection(u'users').document(u'alovelace') doc_ref.set({ u'first': u'Ada', u'last': u'Lovelace', u'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() << '\n'; } else { std::cout << "Error adding document: " << future.error_message() << '\n'; } });
โหนด 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
$docRef = $db->collection('users')->document('lovelace'); $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."); });
ค#
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
โปรดสังเกตว่าเอกสารนี้มีคู่คีย์ - ค่า (ชื่อกลาง) ที่ไม่ปรากฏในเอกสารแรก เอกสารในคอลเลกชันอาจมีชุดข้อมูลที่แตกต่างกัน
เว็บ
// 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); });
รวดเร็ว
// Add a second document with a generated ID. ref = db.collection("users").addDocument(data: [ "first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912 ]) { err in if let err = err { print("Error adding document: \(err)") } else { print("Document added with ID: \(ref!.documentID)") } }
วัตถุประสงค์ -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); } }];
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); } });
โคตรลิน + 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
DocumentReference docRef = db.collection("users").document("aturing"); // Add document data with an additional field ("middle") Map<String, Object> data = new HashMap<>(); data.put("first", "Alan"); data.put("middle", "Mathison"); data.put("last", "Turing"); data.put("born", 1912); ApiFuture<WriteResult> result = docRef.set(data); System.out.println("Update time : " + result.get().getUpdateTime());
Python
doc_ref = db.collection(u'users').document(u'aturing') doc_ref.set({ u'first': u'Alan', u'middle': u'Mathison', u'last': u'Turing', u'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() << '\n'; } else { std::cout << "Error adding document: " << future.error_message() << '\n'; } });
โหนด 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
$docRef = $db->collection('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."); });
ค#
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."
อ่านข้อมูล
หากต้องการตรวจสอบอย่างรวดเร็วว่าคุณได้เพิ่มข้อมูลลงใน Cloud Firestore แล้วให้ใช้โปรแกรมดูข้อมูลใน คอนโซล Firebase
คุณยังสามารถใช้เมธอด "get" เพื่อดึงคอลเล็กชันทั้งหมด
เว็บ
db.collection("users").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); }); });
รวดเร็ว
db.collection("users").getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") } else { for document in querySnapshot!.documents { print("\(document.documentID) => \(document.data())") } } }
วัตถุประสงค์ -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); } } }];
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()); } } });
โคตรลิน + 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
// asynchronously retrieve all users ApiFuture<QuerySnapshot> query = db.collection("users").get(); // ... // query.get() blocks on response QuerySnapshot querySnapshot = query.get(); List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments(); for (QueryDocumentSnapshot document : documents) { System.out.println("User: " + document.getId()); System.out.println("First: " + document.getString("first")); if (document.contains("middle")) { System.out.println("Middle: " + document.getString("middle")); } System.out.println("Last: " + document.getString("last")); System.out.println("Born: " + document.getLong("born")); }
Python
users_ref = db.collection(u'users') docs = users_ref.stream() 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 << '\n'; } } else { std::cout << "Error getting documents: " << future.error_message() << '\n'; } });
โหนด 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
$usersRef = $db->collection('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."); });
ค#
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 หรือ iOS SDK ให้ใช้ Firebase Authentication และ Cloud Firestore Security Rules เพื่อรักษาความปลอดภัยข้อมูลของคุณใน 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;
}
}
}
หากคุณใช้หนึ่งใน SDK ของเซิร์ฟเวอร์ให้ใช้ Identity and Access Management (IAM) เพื่อรักษาความปลอดภัยข้อมูลของคุณใน Cloud Firestore
ดูวิดีโอสอน
สำหรับคำแนะนำโดยละเอียดเกี่ยวกับการเริ่มต้นใช้งานไลบรารีไคลเอ็นต์บนอุปกรณ์เคลื่อนที่และเว็บของ Cloud Firestore โปรดดูวิดีโอบทแนะนำต่อไปนี้:
เว็บ v8.0
iOS
Android
คุณสามารถค้นหาวิดีโอเพิ่มเติมได้ใน ช่อง YouTube ของ Firebase
ขั้นตอนถัดไป
เพิ่มพูนความรู้ของคุณด้วยหัวข้อต่อไปนี้:
- Codelabs - เรียนรู้การใช้ Cloud Firestore ในแอปจริงโดยทำตาม codelab สำหรับ Android , iOS หรือ เว็บ
- โมเดลข้อมูล - เรียนรู้เพิ่มเติมเกี่ยวกับโครงสร้างข้อมูลใน Cloud Firestore รวมถึงข้อมูลตามลำดับชั้นและคอลเล็กชันย่อย
- เพิ่มข้อมูล - เรียนรู้เพิ่มเติมเกี่ยวกับการสร้างและอัปเดตข้อมูลใน Cloud Firestore
- รับข้อมูล - เรียนรู้เพิ่มเติมเกี่ยวกับวิธีดึงข้อมูล
- ดำเนินการค้นหาแบบง่ายและแบบผสม - เรียนรู้วิธีเรียกใช้แบบสอบถามแบบง่ายและแบบผสม
- สั่งซื้อและ จำกัด การสืบค้น เรียนรู้วิธีการสั่งซื้อและ จำกัด ข้อมูลที่ส่งกลับจากคำค้นหาของคุณ