ウェブまたはモバイル クライアント ライブラリを使用して Firestore データベースを作成する

このクイックスタートでは、Android、Apple プラットフォーム、ウェブ、Unity、C++ クライアント ライブラリを使用して Firestore の設定、データの追加、データの読み取りを行う方法を説明します。

Firestore データベースを作成する

  1. まだ Firebase プロジェクトを作成していない場合は作成します。Firebase コンソールで [プロジェクトを追加] をクリックし、画面の指示に沿って、Firebase プロジェクトを作成するか、既存の GCP プロジェクトに Firebase サービスを追加します。

  2. Firebase コンソールのナビゲーション パネルで [Firestore] を選択し、Firestore の [データベースの作成] をクリックします。

  3. Firestore セキュリティ ルールのテストモードを選択します。

    テストモード
    モバイルおよびウェブ クライアント ライブラリを使用する場合に適していますが、すべてのユーザーがデータを読み書きできます。テストが終わったら、必ずデータのセキュリティ保護セクションを確認してください。
  4. データベースのロケーションを選択します。

    • このロケーション設定が、プロジェクトのデフォルトの Google Cloud Platform(GCP)リソース ロケーションになります。なお、このロケーションは、プロジェクト内のロケーション設定が必要な GCP サービスで使用されます。具体例としては、デフォルトの Cloud Storage バケットや App Engine アプリ(Cloud Scheduler を使用する場合に必要)などがあります。

    • ロケーションを選択できない場合は、プロジェクトにデフォルトの GCP リソース ロケーションがすでに設定されています。このロケーションは、プロジェクトの作成時か、ロケーション設定を必要とする別のサービスの設定時に設定されたものです。

  5. [完了] をクリックします。

Firestore を有効にすると、Cloud API Manager で API も有効になります。

開発環境を設定する

必要な依存関係とクライアント ライブラリをアプリに追加します。

Web バージョン 9

  1. Firebase をウェブアプリに追加する手順に従います。
  2. Firebase と Firestore の両方をインポートします。
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";
    

Web バージョン 8

  1. Firebase をウェブアプリに追加する手順に従います。
  2. Firebase と 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>
    Firestore SDK は、npm パッケージとしても提供されています。
    npm install firebase@8.10.1 --save
    
    Firebase と Firestore の両方を手動で require する必要があります。
    const firebase = require("firebase");
    // Required for side-effects
    require("firebase/firestore");
    
Apple プラットフォーム

Firebase を Apple アプリに追加するの手順に沿って操作します。

Swift Package Manager を使用して Firebase の依存関係のインストールと管理を行います。

  1. Xcode でアプリ プロジェクトを開いたまま、[File(ファイル)] > [Swift Packages(Swift パッケージ)] > [Add Package Dependency(パッケージの依存関係を追加)] の順に移動します。
  2. プロンプトが表示されたら、Firebase Apple プラットフォーム SDK リポジトリを追加します。
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. Firestore ライブラリを選択します。
  5. 上記の作業が完了すると、Xcode は依存関係の解決とバックグラウンドでのダウンロードを自動的に開始します。
Android
  1. Android アプリに Firebase を追加するの手順に沿って操作します。
  2. モジュール(アプリレベル)の Gradle ファイル(通常は app/build.gradle.kts または app/build.gradle)で Android 用 Firestore ライブラリの依存関係を宣言します。
    implementation("com.google.firebase:firebase-firestore:24.11.0")

    アプリで複数の Firebase ライブラリを使用する場合は、Firebase Android BoM の使用を検討してください。これを使用すると、アプリで常に互換性のある Firebase ライブラリ バージョンが使用されます。

    Kotlin 固有のライブラリ モジュールをお探しの場合、2023 年 10 月のリリース以降は、Kotlin と Java のどちらのデベロッパーもメイン ライブラリ モジュールを利用できるようになります(詳しくは、このイニシアチブに関するよくある質問をご覧ください)。

Dart

  1. まだ行っていない場合は、Flutter アプリで Firebase の構成と初期化を行います。
  2. Flask プロジェクトのルートから、次のコマンドを実行してプラグインをインストールします。
    flutter pub add cloud_firestore
  3. 完了したら、Kotlin アプリケーションを再ビルドします。
    flutter run
C++
  1. Firebase を C++ プロジェクトに追加するの手順に沿って操作します。
  2. 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}")
              
  3. デスクトップ統合を設定するには、Firebase を C++ プロジェクトに追加するをご覧ください。
Unity
  1. Firebase を Unity プロジェクトに追加するの手順に沿って操作します。
  2. Unity インターフェースを使用して、Android ビルドを最小化するようにプロジェクトを構成します。
  3. メッセージ Error while merging dex archives を避けるには、ビルドを最小化する必要があります。

    • このオプションは [Player Settings] > [Android] > [Publishing Settings] > [Minify] にあります。
    • オプションは Unity のバージョンによって異なる場合があります。公式の Unity ドキュメントFirebase Unity Build Debug ガイドをご覧ください。
    • 圧縮を有効にした後も、参照されるメソッドの数が制限を超える場合は、次の場所で multidex を有効にすることもできます。
      • [Player Settings] の下の [Custom Gradle Template] が有効な場合は、mainTemplate.gradle
      • Android Studio を使用してエクスポートされたプロジェクトをビルドする場合は、モジュール レベルの build.gradle ファイル。

Firestore を初期化する

Firestore のインスタンスを初期化します。

Web バージョン 9

// Initialize Firestore through Firebase
import { initializeApp } from "firebase/app"
import { getFirestore } from "firebase/firestore"
const firebaseApp = initializeApp({
  apiKey: '### FIREBASE API KEY ###',
  authDomain: '### FIREBASE AUTH DOMAIN ###',
  projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});

const db = getFirestore();
「initializeApp」の値は、ウェブアプリの「firebaseConfig」に表示されています。デバイスの接続が失われた場合にデータを維持する方法については、オフライン データの有効化をご覧ください。

Web バージョン 8

// Initialize Firestore through Firebase
firebase.initializeApp({
  apiKey: '### FIREBASE API KEY ###',
  authDomain: '### FIREBASE AUTH DOMAIN ###',
  projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});

var db = firebase.firestore();
「initializeApp」の値は、ウェブアプリの「firebaseConfig」に表示されています。デバイスの接続が失われた場合にデータを維持する方法については、オフライン データの有効化をご覧ください。
Swift
注: このプロダクトは、watchOS と App Clip の各ターゲットでは利用できません。
import FirebaseCore
import FirebaseFirestore

FirebaseApp.configure()

let db = Firestore.firestore()
Objective-C
注: このプロダクトは、watchOS と App Clip の各ターゲットでは利用できません。
@import FirebaseCore;
@import FirebaseFirestore;

// Use Firebase library to configure APIs
[FIRApp configure];

FIRFirestore *defaultFirestore = [FIRFirestore firestore];
  
Kotlin+KTX
Android
  // Access a Firestore instance from your Activity
  val db = Firebase.firestore
Java
Android
// Access a Firestore instance from your Activity
  FirebaseFirestore db = FirebaseFirestore.getInstance();

Dart

db = FirebaseFirestore.instance;
C++
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().
App::Create();
Firestore* db = Firestore::GetInstance();
Unity
using Firebase.Firestore;
using Firebase.Extensions;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;

データの追加

Firestore はデータをドキュメント内に保存します。ドキュメントはコレクション内に保存されます。データを初めてドキュメントに追加すると、Firestore によってコレクションとドキュメントが暗黙的に作成されます。コレクションやドキュメントを明示的に作成する必要はありません。

次のサンプルコードを使用して、新しいコレクションとドキュメントを作成します。

Web バージョン 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 バージョン 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);
});
Swift
注: このプロダクトは、watchOS と App Clip の各ターゲットでは利用できません。
// Add a new document with a generated ID
do {
  let ref = try await db.collection("users").addDocument(data: [
    "first": "Ada",
    "last": "Lovelace",
    "born": 1815
  ])
  print("Document added with ID: \(ref.documentID)")
} catch {
  print("Error adding document: \(error)")
}
Objective-C
注: このプロダクトは、watchOS と App Clip の各ターゲットでは利用できません。
// Add a new document with a generated ID
__block FIRDocumentReference *ref =
    [[self.db collectionWithPath:@"users"] addDocumentWithData:@{
      @"first": @"Ada",
      @"last": @"Lovelace",
      @"born": @1815
    } completion:^(NSError * _Nullable error) {
      if (error != nil) {
        NSLog(@"Error adding document: %@", error);
      } else {
        NSLog(@"Document added with ID: %@", ref.documentID);
      }
    }];
Kotlin+KTX
Android
// 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
Android
// 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 コレクションに追加します。このドキュメントには、最初のドキュメントに表示されない Key-Value ペア(ミドルネーム)が含まれています。コレクション内のドキュメントには、それぞれ異なる情報のセットを含めることができます。

Web バージョン 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 バージョン 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);
});
Swift
注: このプロダクトは、watchOS と App Clip の各ターゲットでは利用できません。
// Add a second document with a generated ID.
do {
  let ref = try await db.collection("users").addDocument(data: [
    "first": "Alan",
    "middle": "Mathison",
    "last": "Turing",
    "born": 1912
  ])
  print("Document added with ID: \(ref.documentID)")
} catch {
  print("Error adding document: \(error)")
}
Objective-C
注: このプロダクトは、watchOS と App Clip の各ターゲットでは利用できません。
// Add a second document with a generated ID.
__block FIRDocumentReference *ref =
    [[self.db collectionWithPath:@"users"] addDocumentWithData:@{
      @"first": @"Alan",
      @"middle": @"Mathison",
      @"last": @"Turing",
      @"born": @1912
    } completion:^(NSError * _Nullable error) {
      if (error != nil) {
        NSLog(@"Error adding document: %@", error);
      } else {
        NSLog(@"Document added with ID: %@", ref.documentID);
      }
    }];
Kotlin+KTX
Android
// 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
Android
// 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 コンソールのデータビューアを使用して、Firestore にデータが追加されたことをすばやく確認します。

get メソッドを使用してコレクション全体を取得することもできます。

Web バージョン 9

import { collection, getDocs } from "firebase/firestore";

const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
  console.log(`${doc.id} => ${doc.data()}`);
});

Web バージョン 8

db.collection("users").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});
Swift
注: このプロダクトは、watchOS と App Clip の各ターゲットでは利用できません。
do {
  let snapshot = try await db.collection("users").getDocuments()
  for document in snapshot.documents {
    print("\(document.documentID) => \(document.data())")
  }
} catch {
  print("Error getting documents: \(error)")
}
Objective-C
注: このプロダクトは、watchOS と App Clip の各ターゲットでは利用できません。
[[self.db collectionWithPath:@"users"]
    getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot,
                                 NSError * _Nullable error) {
      if (error != nil) {
        NSLog(@"Error getting documents: %@", error);
      } else {
        for (FIRDocumentSnapshot *document in snapshot.documents) {
          NSLog(@"%@ => %@", document.documentID, document.data);
        }
      }
    }];
Kotlin+KTX
Android
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
Android
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.");
});

データをセキュリティで保護する

Firebase AuthenticationFirestore セキュリティ ルールを使用して Firestore のデータを保護します。

最初に使用できる基本的なルールセットを以下に示します。セキュリティ ルールは Firebase コンソールの [ルール] タブで変更できます。

認証必須

// 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 アプリを本番環境にデプロイする前に、自分のアプリ クライアントのみが Firestore データにアクセスできるように準備します。アプリチェックのドキュメントをご覧ください。

動画チュートリアルを視聴する

Firestore モバイルおよびウェブ クライアント ライブラリを使用する際の詳しいガイダンスについては、以下のいずれかの動画チュートリアルをご覧ください。

ウェブ
iOS
Android

Firebase の YouTube チャンネルにはさらに多くの動画があります。

次のステップ

次のトピックで知識を深めてください。