このクイックスタートでは、Cloud Firestore を設定してデータを追加し、追加したデータを Firebase コンソールで表示する方法について説明します。
Cloud Firestore データベースを作成する
まだ Firebase プロジェクトを作成していない場合は作成します。Firebase コンソールで [プロジェクトを追加] をクリックし、画面の指示に沿って、Firebase プロジェクトを作成するか、既存の GCP プロジェクトに Firebase サービスを追加します。
コンソールのナビゲーション パネルで [データベース] を選択し、Cloud Firestore の [データベースの作成] をクリックします。
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 を有効にすると、Cloud API Manager で API も有効になります。
開発環境を設定する
必要な依存関係とクライアント ライブラリをアプリに追加します。
ウェブ
- Firebase をウェブアプリに追加する手順に従います。
- Firebase と Cloud Firestore のライブラリをアプリに追加します。
<script src="https://www.gstatic.com/firebasejs/7.2.3/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/7.2.3/firebase-firestore.js"></script>
Cloud Firestore SDK は、npm パッケージとしても提供されています。npm install firebase@7.2.3 --save
Firebase と Cloud Firestore の両方を手動で require する必要があります。const firebase = require("firebase"); // Required for side-effects require("firebase/firestore");
iOS
- Firebase を iOS アプリに追加する手順に従います。
Podfile
に Cloud Firestore ポッドを追加します。pod 'Firebase/Core' pod 'Firebase/Firestore' # Optionally, include the Swift extensions if you're using Swift. pod 'FirebaseFirestoreSwift'
- ファイルを保存して
pod install
を実行します。
Java
- Android アプリに Firebase を追加する手順に従います。
- プロジェクト レベルの
build.gradle
ファイルにおいて、buildscript
セクションとallprojects
セクションの両方に Google の Maven リポジトリを組み込みます。 -
Cloud Firestore Android ライブラリを
app/build.gradle
ファイルに追加します。implementation 'com.google.firebase:firebase-firestore:21.2.1'
Kotlin
- Android アプリに Firebase を追加する手順に従います。
- プロジェクト レベルの
build.gradle
ファイルにおいて、buildscript
セクションとallprojects
セクションの両方に Google の Maven リポジトリを組み込みます。 -
Cloud Firestore Android ライブラリを
app/build.gradle
ファイルに追加します。implementation 'com.google.firebase:firebase-firestore:21.2.1'
Java
- アプリに Firebase Admin SDK を追加します。
-
Gradle を使用する:
compile 'com.google.firebase:firebase-admin:6.11.0'
-
Maven を使用する:
<dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>6.11.0</version> </dependency>
-
Gradle を使用する:
- 以下の手順に従い、ご使用の環境で適切な認証情報を使用して Cloud Firestore を初期化します。
Python
- Firebase Admin SDK を Python アプリに追加します。
pip install --upgrade firebase-admin
- 以下の手順に従い、ご使用の環境で適切な認証情報を使用して Cloud Firestore を初期化します。
Node.js
-
アプリに Firebase Admin SDK を追加します。
npm install firebase-admin --save
- 以下の手順に従い、ご使用の環境で適切な認証情報を使用して Cloud Firestore を初期化します。
Go
- 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 Console の認証情報ページで作成できます。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
C#
-
Cloud Firestore サーバーのクライアント ライブラリ(Java、Node.js、Python、Go、PHP、C#、Ruby)は、認証に Google アプリケーションのデフォルト認証情報を使用します。
-
開発環境から認証するには、JSON サービス アカウント キーファイルを指すように
GOOGLE_APPLICATION_CREDENTIALS
環境変数を設定します。キーファイルは、API Console の認証情報ページで作成できます。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;
Ruby
-
Cloud Firestore サーバーのクライアント ライブラリ(Java、Node.js、Python、Go、PHP、C#、Ruby)は、認証に Google アプリケーションのデフォルト認証情報を使用します。
-
開発環境から認証するには、JSON サービス アカウント キーファイルを指すように
GOOGLE_APPLICATION_CREDENTIALS
環境変数を設定します。キーファイルは、API Console の認証情報ページで作成できます。export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 本番環境では、Cloud Firestore で使用するプロジェクトと同じプロジェクトを使用して App Engine または Compute Engine でアプリケーションを実行する場合は、認証する必要はありません。それ以外の場合は、サービス アカウントの設定が必要です。
-
開発環境から認証するには、JSON サービス アカウント キーファイルを指すように
-
Gemfile
でアプリに Cloud Firestore Ruby ライブラリを追加します。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();デバイスの接続が失われた場合にデータを維持する方法については、オフライン データの有効化をご覧ください。
Swift
import Firebase FirebaseApp.configure() let db = Firestore.firestore()
Objective-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();
Kotlin
// Access a Cloud Firestore instance from your Activity val db = FirebaseFirestore.getInstance()
Java
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 を使用するには、サービス アカウントを使用します。
Cloud Platform 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();
Python
Cloud Firestore SDK を初期化する方法は環境に応じて異なります。最も一般的な方法を以下に示します。完全なリファレンスについては、Admin 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, { 'projectId': project_id, }) db = firestore.client()
各自のサーバーで Firebase Admin SDK を使用するには、サービス アカウントを使用します。
Cloud Platform 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') firebase_admin.initialize_app(cred) db = firestore.client()
Node.js
Cloud Firestore SDK を初期化する方法は環境に応じて異なります。最も一般的な方法を以下に示します。完全なリファレンスについては、Admin SDK の初期化をご覧ください。-
Cloud Functions で初期化する
const admin = require('firebase-admin');const functions = require('firebase-functions'); admin.initializeApp(functions.config().firebase); let db = admin.firestore();
-
Google Cloud Platform で初期化する
const admin = require('firebase-admin'); admin.initializeApp({ credential: admin.credential.applicationDefault() }); const db = admin.firestore(); // ...
-
各自のサーバーで初期化する
各自のサーバー(またはその他の Node.js 環境)で Firebase Admin SDK を使用するには、サービス アカウントを使用します。Cloud Platform Console で [IAM と管理] > [サービス アカウント] にアクセスします。新しい秘密鍵を生成し、JSON ファイルを保存します。次に、このファイルを使用して SDK を初期化します。
const admin = require('firebase-admin'); let serviceAccount = require('path/to/serviceAccountKey.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }); let db = admin.firestore();
Go
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 を使用するには、サービス アカウントを使用します。
Cloud Platform 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
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); }
C#
FirestoreDb db = FirestoreDb.Create(project); Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
Ruby
require "google/cloud/firestore" firestore = Google::Cloud::Firestore.new project_id: project_id puts "Created Cloud Firestore client with given project ID."
データを追加する
Cloud Firestore はデータをドキュメントに保存します。ドキュメントはコレクションに保存されます。データを初めてドキュメントに追加すると、Cloud Firestore によってコレクションとドキュメントが暗黙的に作成されます。コレクションやドキュメントを明示的に作成する必要はありません。
次のサンプルコードを使用して、新しいコレクションとドキュメントを作成します。
ウェブ
db.collection("users").add({ first: "Ada", last: "Lovelace", born: 1815 }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); }) .catch(function(error) { console.error("Error adding document: ", error); });
Swift
// 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)") } }
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); } }];
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); } });
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
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 })
Node.js
let docRef = db.collection('users').doc('alovelace'); let setAda = docRef.set({ first: 'Ada', last: 'Lovelace', born: 1815 });
Go
_, _, 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);
C#
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);
Ruby
doc_ref = firestore.doc "users/alovelace" doc_ref.set( first: "Ada", last: "Lovelace", born: 1815 ) puts "Added data to the alovelace document in the users collection."
次に、別のドキュメントを users
コレクションに追加します。このドキュメントには、最初のドキュメントに表示されない key-value ペア(ミドルネーム)が含まれています。コレクション内のドキュメントには、それぞれ異なる情報のセットを含めることができます。
ウェブ
// Add a second document with a generated ID. db.collection("users").add({ first: "Alan", middle: "Mathison", last: "Turing", born: 1912 }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); }) .catch(function(error) { console.error("Error adding document: ", error); });
Swift
// 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)") } }
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); } }];
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); } });
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
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 })
Node.js
let aTuringRef = db.collection('users').doc('aturing'); let setAlan = aTuringRef.set({ 'first': 'Alan', 'middle': 'Mathison', 'last': 'Turing', 'born': 1912 });
Go
_, _, 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);
C#
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);
Ruby
doc_ref = firestore.doc "users/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()}`); }); });
Swift
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())") } } }
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); } } }];
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()); } } });
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
// 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(u'{} => {}'.format(doc.id, doc.to_dict()))
Node.js
db.collection('users').get() .then((snapshot) => { snapshot.forEach((doc) => { console.log(doc.id, '=>', doc.data()); }); }) .catch((err) => { console.log('Error getting documents', err); });
Go
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);
C#
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(); }
Ruby
users_ref = firestore.col "users" users_ref.get do |user| puts "#{user.document_id} data: #{user.data}." end
データをセキュリティで保護する
ウェブ、Android、または iOS SDK を使用している場合は、Firebase Authentication と 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.uid != 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 モバイルおよびウェブ クライアント ライブラリを使用する際の詳しいガイダンスについては、以下のいずれかの動画チュートリアルをご覧ください。
ウェブ
iOS
Android
Firebase の YouTube チャンネルにはさらに多くの動画があります。
次のステップ
次のトピックで知識を深めてください。
- Codelab - Android、iOS、またはウェブの Codelab に従い、実際のアプリで Cloud Firestore を使用する方法を学習します。
- データモデル - 階層データやサブコレクションなど、データが Cloud Firestore で構造化される仕組みを学習します。
- データを追加する - Cloud Firestore でデータを作成および更新する方法を学習します。
- データを取得する - データを取得する方法を学習します。
- 単純なクエリと複合クエリを実行する - 単純なクエリと複合クエリを実行する方法を学習します。
- クエリの並べ替えと制限 - クエリによって返されるデータを並べ替え、制限する方法を学習します。