이 빠른 시작에서는 Cloud Firestore를 설정하고 데이터를 추가한 다음 Firebase 콘솔에서 방금 추가한 데이터를 보는 방법을 보여줍니다.
Cloud Firestore 데이터베이스 만들기
Firebase 프로젝트를 아직 만들지 않은 경우 Firebase 콘솔 에서 프로젝트 추가 를 클릭한 다음 화면의 안내에 따라 Firebase 프로젝트를 만들거나 기존 GCP 프로젝트에 Firebase 서비스를 추가합니다.
Firebase 콘솔 의 Cloud Firestore 섹션으로 이동합니다. 기존 Firebase 프로젝트를 선택하라는 메시지가 표시됩니다. 데이터베이스 생성 워크플로우를 따르십시오.
Cloud Firestore 보안 규칙의 시작 모드를 선택합니다.
- 시험 모드
모바일 및 웹 클라이언트 라이브러리를 시작하는 데 적합하지만 누구나 데이터를 읽고 덮어쓸 수 있습니다. 테스트 후 데이터 보안 섹션을 검토하십시오.
웹, Apple 플랫폼 또는 Android SDK를 시작하려면 테스트 모드를 선택하십시오.
- 잠금 모드
모바일 및 웹 클라이언트의 모든 읽기 및 쓰기를 거부합니다. 인증된 애플리케이션 서버(C#, Go, Java, Node.js, PHP, Python 또는 Ruby)는 계속해서 데이터베이스에 액세스할 수 있습니다.
C#, Go, Java, Node.js, PHP, Python 또는 Ruby 서버 클라이언트 라이브러리를 시작하려면 잠금 모드를 선택하세요.
데이터베이스의 위치 를 선택하십시오.
이 위치 설정은 프로젝트의 기본 Google Cloud Platform(GCP) 리소스 위치 입니다. 이 위치는 특히 기본 Cloud Storage 버킷 및 App Engine 앱(Cloud Scheduler를 사용하는 경우 필요함)과 같이 위치 설정이 필요한 프로젝트의 GCP 서비스에 사용됩니다.
위치를 선택할 수 없다면 프로젝트에 이미 기본 GCP 리소스 위치가 있는 것입니다. 프로젝트 생성 중 또는 위치 설정이 필요한 다른 서비스를 설정할 때 설정되었습니다.
완료 를 클릭합니다.
Cloud Firestore를 활성화하면 Cloud API Manager 에서 API도 활성화됩니다.
개발 환경 설정
필요한 종속성 및 클라이언트 라이브러리를 앱에 추가합니다.
Web version 8
- 지침에 따라 웹 앱에 Firebase를 추가합니다 .
- Firebase 및 Cloud Firestore 라이브러리를 앱에 추가합니다.
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-firestore.js"></script>
Cloud Firestore SDK는 npm 패키지로도 제공됩니다.npm install firebase@8.10.1 --save
Firebase와 Cloud Firestore를 모두 수동으로 요구해야 합니다.const firebase = require("firebase"); // Required for side-effects require("firebase/firestore");
Web version 9
- 지침에 따라 웹 앱에 Firebase를 추가합니다 .
- Cloud Firestore SDK는 npm 패키지로 제공됩니다.
npm install firebase@9.16.0 --save
Firebase와 Cloud Firestore를 모두 가져와야 합니다.import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore";
iOS+
안내에 따라 Firebase를 Apple 앱에 추가합니다 .
Swift Package Manager를 사용하여 Firebase 종속 항목을 설치하고 관리합니다.
- Xcode에서 앱 프로젝트를 연 상태에서 File > Swift Packages > Add Package Dependency 로 이동합니다.
- 메시지가 표시되면 Firebase Apple 플랫폼 SDK 저장소를 추가합니다.
- Firestore 라이브러리를 선택합니다.
- 완료되면 Xcode는 자동으로 백그라운드에서 종속성을 해결하고 다운로드하기 시작합니다.
https://github.com/firebase/firebase-ios-sdk
Kotlin+KTX
- 지침에 따라 Android 앱에 Firebase를 추가합니다 .
- Firebase Android BoM 을 사용하여 모듈(앱 수준) Gradle 파일 (일반적으로
app/build.gradle
)에서 Cloud Firestore Android 라이브러리에 대한 종속성을 선언합니다.dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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 라이브러리를 사용합니다.
(대안) BoM을 사용 하지 않고 Firebase 라이브러리 종속성 선언
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:24.4.2' }
Java
- 지침에 따라 Android 앱에 Firebase를 추가합니다 .
- Firebase Android BoM 을 사용하여 모듈(앱 수준) Gradle 파일 (일반적으로
app/build.gradle
)에서 Cloud Firestore Android 라이브러리에 대한 종속성을 선언합니다.dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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 라이브러리를 사용합니다.
(대안) BoM을 사용 하지 않고 Firebase 라이브러리 종속성 선언
Firebase BoM을 사용하지 않기로 선택한 경우 종속성 줄에 각 Firebase 라이브러리 버전을 지정해야 합니다.
앱에서 여러 Firebase 라이브러리를 사용하는 경우 BoM을 사용하여 모든 버전이 호환되도록 라이브러리 버전을 관리하는 것이 좋습니다.
dependencies { // Declare the dependency for the Cloud Firestore library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-firestore:24.4.2' }
Dart
- 아직 하지 않았다면 Flutter 앱에서 Firebase를 구성하고 초기화 합니다.
- Flutter 프로젝트의 루트에서 다음 명령을 실행하여 플러그인을 설치합니다:
flutter pub add cloud_firestore
- 완료되면 Flutter 애플리케이션을 다시 빌드합니다.
flutter run
- 선택 사항: 미리 컴파일된 프레임워크를 포함하여 iOS 및 macOS 빌드 시간을 개선합니다.
현재 iOS용 Firestore SDK는 Xcode에서 빌드하는 데 5분 이상 걸릴 수 있는 코드에 의존합니다. 빌드 시간을 크게 줄이려면 Podfile의
target 'Runner' do
블록에 다음 줄을 추가하여 미리 컴파일된 버전을 사용할 수 있습니다.target 'Runner' do pod 'FirebaseFirestore', :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git', :tag => '8.15.0' # ... end
또한 CocoaPods를 1.9.1 이상으로 업그레이드했는지 확인하십시오.
gem install cocoapods
자세한 내용은 GitHub의 문제를 참조하세요.
자바
- 앱에 Firebase Admin SDK를 추가합니다.
- Gradle 사용:
compile 'com.google.firebase:firebase-admin:1.32.0'
- Maven 사용:
<dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>1.32.0</version> </dependency>
- Gradle 사용:
- 아래 안내에 따라 환경에서 적절한 자격 증명으로 Cloud Firestore를 초기화하세요.
파이썬
- Python 앱에 Firebase Admin SDK 추가:
pip install --upgrade firebase-admin
- 아래 안내에 따라 환경에서 적절한 자격 증명으로 Cloud Firestore를 초기화하세요.
C++
- 안내에 따라 Firebase를 C++ 프로젝트에 추가합니다 .
- Android용 C++ 인터페이스.
- 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}")
- 데스크톱 통합 을 설정하려면 C++ 프로젝트에 Firebase 추가 를 참조하세요.
단일성
- 지침에 따라 Unity 프로젝트에 Firebase를 추가합니다 .
- Android용 Unity 인터페이스.
- 파일 > 빌드 설정을 선택합니다.
- '플랫폼'을 'Android'로 전환하고 '플랫폼 전환'을 클릭합니다.
- '플레이어 설정...'을 클릭합니다.
- 기본 Unity UI의 'Android용 설정'에서 '게시 설정'을 선택합니다.
- 'Minify' 섹션에서 Release 및 Debug 설정을 모두 'None'에서 'ProGuard'로 변경합니다.
Android용으로 빌드할 때 ProGuarding을 활성화하여 Android DEX 제한을 피하십시오. 이렇게 하려면 Unity 편집기에서 다음을 수행합니다.
Node.js
- 앱에 Firebase Admin SDK 추가:
npm install firebase-admin --save
- 아래 안내에 따라 환경에서 적절한 자격 증명으로 Cloud Firestore를 초기화하세요.
가다
- Go 앱에 Firebase Admin SDK 추가:
go get firebase.google.com/go
- 아래 안내에 따라 환경에서 적절한 자격 증명으로 Cloud Firestore를 초기화하세요.
PHP
- Cloud Firestore 서버 클라이언트 라이브러리(Java, Node.js, Python, Go, PHP, C# 및 Ruby)는 인증을 위해 Google 애플리케이션 기본 자격 증명 을 사용합니다.
- 개발 환경에서 인증하려면 JSON 서비스 계정 키 파일을 가리키도록
GOOGLE_APPLICATION_CREDENTIALS
환경 변수를 설정합니다. API 콘솔 자격 증명 페이지 에서 키 파일을 생성할 수 있습니다.export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 프로덕션 환경에서 Cloud Firestore에 사용하는 것과 동일한 프로젝트를 사용하여 App Engine 또는 Compute Engine에서 애플리케이션을 실행하는 경우 인증할 필요가 없습니다. 그렇지 않으면 서비스 계정을 설정합니다 .
- 개발 환경에서 인증하려면 JSON 서비스 계정 키 파일을 가리키도록
- 클라이언트 라이브러리를 사용해야 하는 PHP용 gRPC 확장 을 설치하고 활성화합니다.
- 앱에 Cloud Firestore PHP 라이브러리 추가:
composer require google/cloud-firestore
씨#
- Cloud Firestore 서버 클라이언트 라이브러리(Java, Node.js, Python, Go, PHP, C# 및 Ruby)는 인증을 위해 Google 애플리케이션 기본 자격 증명 을 사용합니다.
- 개발 환경에서 인증하려면 JSON 서비스 계정 키 파일을 가리키도록
GOOGLE_APPLICATION_CREDENTIALS
환경 변수를 설정합니다. API 콘솔 자격 증명 페이지 에서 키 파일을 생성할 수 있습니다.export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 프로덕션 환경에서 Cloud Firestore에 사용하는 것과 동일한 프로젝트를 사용하여 App Engine 또는 Compute Engine에서 애플리케이션을 실행하는 경우 인증할 필요가 없습니다. 그렇지 않으면 서비스 계정을 설정합니다 .
- 개발 환경에서 인증하려면 JSON 서비스 계정 키 파일을 가리키도록
-
.csproj
파일의 앱에 Cloud Firestore C# 라이브러리를 추가합니다.<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 애플리케이션 기본 자격 증명 을 사용합니다.
- 개발 환경에서 인증하려면 JSON 서비스 계정 키 파일을 가리키도록
GOOGLE_APPLICATION_CREDENTIALS
환경 변수를 설정합니다. API 콘솔 자격 증명 페이지 에서 키 파일을 생성할 수 있습니다.export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 프로덕션 환경에서 Cloud Firestore에 사용하는 것과 동일한 프로젝트를 사용하여 App Engine 또는 Compute Engine에서 애플리케이션을 실행하는 경우 인증할 필요가 없습니다. 그렇지 않으면 서비스 계정을 설정합니다 .
- 개발 환경에서 인증하려면 JSON 서비스 계정 키 파일을 가리키도록
-
Gemfile
의 앱에 Cloud Firestore Ruby 라이브러리를 추가합니다.gem "google-cloud-firestore"
-
bundle install
를 사용하여Gemfile
에서 종속성을 설치합니다.
(선택사항) Firebase 로컬 에뮬레이터 도구 모음으로 프로토타입 제작 및 테스트
모바일 개발자를 위해 앱이 Cloud Firestore에서 읽고 쓰는 방법에 대해 이야기하기 전에 Cloud Firestore 기능의 프로토타입을 만들고 테스트하는 데 사용할 수 있는 일련의 도구인 Firebase 로컬 에뮬레이터 도구 모음을 소개하겠습니다. 다른 데이터 모델을 시도하거나 보안 규칙을 최적화하거나 백엔드와 상호 작용하는 가장 비용 효율적인 방법을 찾기 위해 노력하는 경우 라이브 서비스를 배포하지 않고 로컬에서 작업할 수 있는 것이 좋습니다.
Cloud Firestore 에뮬레이터는 앱이 에뮬레이션된 데이터베이스 콘텐츠 및 구성은 물론 선택적으로 에뮬레이션된 프로젝트 리소스(함수, 기타 데이터베이스 및 보안 규칙)와 상호 작용할 수 있게 해주는 로컬 에뮬레이터 도구 모음의 일부입니다.
Cloud Firestore 에뮬레이터를 사용하려면 몇 단계만 거치면 됩니다.
- 에뮬레이터에 연결하기 위해 앱의 테스트 구성에 코드 줄을 추가합니다.
- 로컬 프로젝트 디렉터리의 루트에서
firebase emulators:start
를 실행합니다. - 평소와 같이 Cloud Firestore 플랫폼 SDK를 사용하여 앱의 프로토타입 코드에서 호출합니다.
Cloud Firestore 및 Cloud Functions와 관련된 자세한 연습을 사용할 수 있습니다. Local Emulator Suite 소개 도 살펴봐야 합니다.
Cloud Firestore 초기화
Cloud Firestore의 인스턴스를 초기화합니다.
Web version 9
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 version 8
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
로 바꿉니다.
장치 연결이 끊어졌을 때 데이터를 유지하려면 오프라인 데이터 사용 설명서를 참조하십시오.
빠른
import FirebaseCore import FirebaseFirestore
FirebaseApp.configure() let db = Firestore.firestore()표시자33
목표-C
@import FirebaseCore; @import FirebaseFirestore; // 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();
Kotlin+KTX
// Access a Cloud Firestore instance from your Activity
val db = Firebase.firestore
Dart
db = FirebaseFirestore.instance;
자바
Cloud Firestore SDK는 환경에 따라 다양한 방식으로 초기화됩니다. 다음은 가장 일반적인 방법입니다. 전체 참조 는 Admin SDK 초기화 를 참조하십시오.import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.firestore.Firestore; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; // Use the application default credentials GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(credentials) .setProjectId(projectId) .build(); FirebaseApp.initializeApp(options); Firestore db = FirestoreClient.getFirestore();에서 초기화
자체 서버에서 Firebase Admin SDK를 사용하려면 서비스 계정 을 사용하세요.
Google Cloud Console에서 IAM 및 관리자 > 서비스 계정 으로 이동합니다. 새 개인 키를 생성하고 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();
파이썬
Cloud Firestore SDK는 환경에 따라 다양한 방식으로 초기화됩니다. 다음은 가장 일반적인 방법입니다. 전체 참조 는 Admin SDK 초기화 를 참조하십시오.import firebase_admin from firebase_admin import firestore # Application Default credentials are automatically created. app = firebase_admin.initialize_app() db = firestore.client()에서 초기화
기존 애플리케이션 기본 자격 증명을 사용하여 SDK를 초기화할 수도 있습니다.
import firebase_admin from firebase_admin import credentials from firebase_admin import firestore # Use the application default credentials. cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred) db = firestore.client()
자체 서버에서 Firebase Admin SDK를 사용하려면 서비스 계정 을 사용하세요.
Google Cloud Console에서 IAM 및 관리자 > 서비스 계정 으로 이동합니다. 새 개인 키를 생성하고 JSON 파일을 저장합니다. 그런 다음 파일을 사용하여 SDK를 초기화합니다.
import firebase_admin from firebase_admin import credentials from firebase_admin import firestore # Use a service account. cred = credentials.Certificate('path/to/serviceAccount.json') app = firebase_admin.initialize_app(cred) db = firestore.client()
Python
Cloud Firestore SDK는 환경에 따라 다양한 방식으로 초기화됩니다. 다음은 가장 일반적인 방법입니다. 전체 참조 는 Admin SDK 초기화 를 참조하십시오.import firebase_admin from firebase_admin import firestore_async # Application Default credentials are automatically created. app = firebase_admin.initialize_app() db = firestore_async.client()에서 초기화
기존 애플리케이션 기본 자격 증명을 사용하여 SDK를 초기화할 수도 있습니다.
import firebase_admin from firebase_admin import credentials from firebase_admin import firestore_async # Use the application default credentials. cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred) db = firestore_async.client()
자체 서버에서 Firebase Admin SDK를 사용하려면 서비스 계정 을 사용하세요.
Google Cloud Console에서 IAM 및 관리자 > 서비스 계정 으로 이동합니다. 새 개인 키를 생성하고 JSON 파일을 저장합니다. 그런 다음 파일을 사용하여 SDK를 초기화합니다.
import firebase_admin from firebase_admin import credentials from firebase_admin import firestore_async # Use a service account. cred = credentials.Certificate('path/to/serviceAccount.json') app = firebase_admin.initialize_app(cred) db = firestore_async.client()
C++
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance(). App::Create(); Firestore* db = Firestore::GetInstance();
Node.js
Cloud Firestore SDK는 환경에 따라 다양한 방식으로 초기화됩니다. 다음은 가장 일반적인 방법입니다. 전체 참조 는 Admin SDK 초기화 를 참조하십시오.- Cloud Functions
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
initializeApp(); const db = getFirestore();
에서 초기화 - Google Cloud에서 초기화
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
initializeApp({ credential: applicationDefault() }); const db = getFirestore();
- 자체 서버에서 초기화
자체 서버(또는 다른 Node.js 환경)에서 Firebase Admin SDK를 사용하려면 서비스 계정 을 사용하세요. Google Cloud Console에서 IAM 및 관리자 > 서비스 계정 으로 이동합니다. 새 개인 키를 생성하고 JSON 파일을 저장합니다. 그런 다음 파일을 사용하여 SDK를 초기화합니다.
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
const serviceAccount = require('./path/to/serviceAccountKey.json'); initializeApp({ credential: cert(serviceAccount) }); const db = getFirestore();
가다
Cloud Firestore SDK는 환경에 따라 다양한 방식으로 초기화됩니다. 다음은 가장 일반적인 방법입니다. 전체 참조 는 Admin SDK 초기화 를 참조하십시오.import ( "log" firebase "firebase.google.com/go" "google.golang.org/api/option" ) // Use the application default credentials ctx := context.Background() conf := &firebase.Config{ProjectID: projectID} app, err := firebase.NewApp(ctx, conf) if err != nil { log.Fatalln(err) } client, err := app.Firestore(ctx) if err != nil { log.Fatalln(err) } defer client.Close()에서 초기화
자체 서버에서 Firebase Admin SDK를 사용하려면 서비스 계정 을 사용하세요.
Google Cloud Console에서 IAM 및 관리자 > 서비스 계정 으로 이동합니다. 새 개인 키를 생성하고 JSON 파일을 저장합니다. 그런 다음 파일을 사용하여 SDK를 초기화합니다.
import ( "log" firebase "firebase.google.com/go" "google.golang.org/api/option" ) // Use a service account ctx := context.Background() sa := option.WithCredentialsFile("path/to/serviceAccount.json") app, err := firebase.NewApp(ctx, nil, sa) if err != nil { log.Fatalln(err) } client, err := app.Firestore(ctx) if err != nil { log.Fatalln(err) } defer client.Close()
PHP
PHP
Cloud Firestore 클라이언트 설치 및 생성에 대한 자세한 내용은 Cloud Firestore 클라이언트 라이브러리 를 참조하세요.
단일성
using Firebase.Firestore; using Firebase.Extensions;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
씨#
씨#
Cloud Firestore 클라이언트 설치 및 생성에 대한 자세한 내용은 Cloud Firestore 클라이언트 라이브러리 를 참조하세요.
루비
데이터 추가
Cloud Firestore는 컬렉션에 저장되는 문서에 데이터를 저장합니다. Cloud Firestore는 문서에 데이터를 처음 추가할 때 암묵적으로 컬렉션과 문서를 생성합니다. 컬렉션이나 문서를 명시적으로 만들 필요가 없습니다.
다음 예제 코드를 사용하여 새 컬렉션과 문서를 만듭니다.
Web version 9
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 version 8
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); } }];
Kotlin+KTX
// Create a new user with a first and last name val user = hashMapOf( "first" to "Ada", "last" to "Lovelace", "born" to 1815 ) // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener { documentReference -> Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}") } .addOnFailureListener { e -> Log.w(TAG, "Error adding document", e) }
Java
// Create a new user with a first and last name Map<String, Object> user = new HashMap<>(); user.put("first", "Ada"); user.put("last", "Lovelace"); user.put("born", 1815); // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } });
Dart
// Create a new user with a first and last name final user = <String, dynamic>{ "first": "Ada", "last": "Lovelace", "born": 1815 }; // Add a new document with a generated ID db.collection("users").add(user).then((DocumentReference doc) => print('DocumentSnapshot added with ID: ${doc.id}'));
자바
파이썬
Python
C++
// Add a new document with a generated ID Future<DocumentReference> user_ref = db->Collection("users").Add({{"first", FieldValue::String("Ada")}, {"last", FieldValue::String("Lovelace")}, {"born", FieldValue::Integer(1815)}}); user_ref.OnCompletion([](const Future<DocumentReference>& future) { if (future.error() == Error::kErrorOk) { std::cout << "DocumentSnapshot added with ID: " << future.result()->id() << std::endl; } else { std::cout << "Error adding document: " << future.error_message() << std::endl; } });
Node.js
가다
PHP
PHP
Cloud Firestore 클라이언트 설치 및 생성에 대한 자세한 내용은 Cloud Firestore 클라이언트 라이브러리 를 참조하세요.
단일성
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 version 9
// 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 version 8
// 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); } }];
Kotlin+KTX
// Create a new user with a first, middle, and last name val user = hashMapOf( "first" to "Alan", "middle" to "Mathison", "last" to "Turing", "born" to 1912 ) // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener { documentReference -> Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}") } .addOnFailureListener { e -> Log.w(TAG, "Error adding document", e) }
Java
// Create a new user with a first, middle, and last name Map<String, Object> user = new HashMap<>(); user.put("first", "Alan"); user.put("middle", "Mathison"); user.put("last", "Turing"); user.put("born", 1912); // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } });
Dart
// Create a new user with a first and last name final user = <String, dynamic>{ "first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912 }; // Add a new document with a generated ID db.collection("users").add(user).then((DocumentReference doc) => print('DocumentSnapshot added with ID: ${doc.id}'));
자바
파이썬
Python
C++
db->Collection("users") .Add({{"first", FieldValue::String("Alan")}, {"middle", FieldValue::String("Mathison")}, {"last", FieldValue::String("Turing")}, {"born", FieldValue::Integer(1912)}}) .OnCompletion([](const Future<DocumentReference>& future) { if (future.error() == Error::kErrorOk) { std::cout << "DocumentSnapshot added with ID: " << future.result()->id() << std::endl; } else { std::cout << "Error adding document: " << future.error_message() << std::endl; } });
Node.js
가다
PHP
PHP
Cloud Firestore 클라이언트 설치 및 생성에 대한 자세한 내용은 Cloud Firestore 클라이언트 라이브러리 를 참조하세요.
단일성
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 콘솔 에서 데이터 뷰어를 사용하세요.
"get" 메소드를 사용하여 전체 컬렉션을 검색할 수도 있습니다.
Web version 9
import { collection, getDocs } from "firebase/firestore"; const querySnapshot = await getDocs(collection(db, "users")); querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); });
Web version 8
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); } } }];
Kotlin+KTX
db.collection("users") .get() .addOnSuccessListener { result -> for (document in result) { Log.d(TAG, "${document.id} => ${document.data}") } } .addOnFailureListener { exception -> Log.w(TAG, "Error getting documents.", exception) }
Java
db.collection("users") .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { Log.d(TAG, document.getId() + " => " + document.getData()); } } else { Log.w(TAG, "Error getting documents.", task.getException()); } } });
Dart
await db.collection("users").get().then((event) { for (var doc in event.docs) { print("${doc.id} => ${doc.data()}"); } });
자바
파이썬
users_ref = db.collection(u'users') docs = users_ref.stream() for doc in docs: print(f'{doc.id} => {doc.to_dict()}')
Python
C++
Future<QuerySnapshot> users = db->Collection("users").Get(); users.OnCompletion([](const Future<QuerySnapshot>& future) { if (future.error() == Error::kErrorOk) { for (const DocumentSnapshot& document : future.result()->documents()) { std::cout << document << std::endl; } } else { std::cout << "Error getting documents: " << future.error_message() << std::endl; } });
Node.js
가다
PHP
PHP
Cloud Firestore 클라이언트 설치 및 생성에 대한 자세한 내용은 Cloud Firestore 클라이언트 라이브러리 를 참조하세요.
단일성
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."); });
씨#
루비
데이터 보안
웹, Android 또는 Apple 플랫폼 SDK를 사용하는 경우 Firebase 인증 및 Cloud Firestore 보안 규칙 을 사용하여 Cloud Firestore의 데이터를 보호하세요.
다음은 시작하는 데 사용할 수 있는 몇 가지 기본 규칙 세트입니다. 콘솔의 규칙 탭 에서 보안 규칙을 수정할 수 있습니다.
인증 필요
// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
잠금 모드
// Deny read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
시험 모드
// Allow read/write access to all users under any conditions
// Warning: **NEVER** use this rule set in production; it allows
// anyone to overwrite your entire database.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
웹, Android 또는 iOS 앱을 프로덕션에 배포하기 전에 앱 클라이언트만 Cloud Firestore 데이터에 액세스할 수 있도록 조치를 취하십시오. 앱 체크 문서를 참조하세요.
서버 SDK 중 하나를 사용하는 경우 Identity and Access Management(IAM) 를 사용하여 Cloud Firestore의 데이터를 보호하세요.
비디오 튜토리얼 보기
Cloud Firestore 모바일 클라이언트 라이브러리를 시작하는 방법에 대한 자세한 안내는 다음 동영상 자습서 중 하나를 시청하세요.
편물
iOS+
기계적 인조 인간
Firebase YouTube 채널 에서 더 많은 동영상을 찾을 수 있습니다.
다음 단계
다음 주제로 지식을 심화하십시오.
- Codelab — Android , iOS 또는 Web 용 Codelab을 따라 실제 앱에서 Cloud Firestore를 사용하는 방법을 알아보세요.
- 데이터 모델 — 계층적 데이터 및 하위 컬렉션을 포함하여 Cloud Firestore에서 데이터가 구성되는 방식에 대해 자세히 알아보세요.
- 데이터 추가 — Cloud Firestore에서 데이터 생성 및 업데이트에 대해 자세히 알아보세요.
- 데이터 가져오기 — 데이터 검색 방법에 대해 자세히 알아보세요.
- 단순 및 복합 쿼리 수행 - 단순 및 복합 쿼리 를 실행하는 방법을 알아봅니다.
- 쿼리 정렬 및 제한 쿼리에서 반환된 데이터를 정렬하고 제한하는 방법을 알아봅니다.