PUROGU LADESU

ポエムがメインのブログです。

【Firebase with Expo】Firestoreの使い方まとめ

Firestore

Firebaseが提供するデータベースシステムです。仕組みはKeyValueStoreの構造を持つNoSQLとなります。 FirebaseにはRealtimeDatabaseというサービスもありますがFirestoreのほうが新しいようです。

Cloud Firestore  |  Firebase

3階層

collection (RDBのテーブルみたいなもの)
-> document (RDBの行+主キーみたいなもの)
-> field (RDBの各フィールドみたいなもの)

documentにcollectionを入れてネストすることもできる

初期化

Cloud Firestore を使ってみる  |  Firebase

firebase.initializeApp(config);
const db = firebase.firestore();

データの追加

.add(...) と .doc().set(...) は完全に同等。

Add data to Cloud Firestore  |  Firebase

  • setはidを指定
  db.collection("user").doc("testuserid").set({name: yoshida, age: 30});
  • addはidは自動生成
  db.collection("user").add({name: yoshida, age: 30});

更新

setは全部置き換えるが、updateは一部を更新できる。 ドット表記でネストした値を指定可能。

db.collection("user").doc("testuserid").update({age: 32})

タイムスタンプ

db.collection("user").doc("testuserid").update({
  timestamp: firebase.firestore.FieldValue.serverTimestamp()
})

データの取得

db.collection("user").doc("testuserid").get()
  • クエリ
  ref.orderBy("name", "desc").limit(3)
  // whereとorderbyは同じフィールドにする必要がある
  ref.where("population", ">", 100000).orderBy("population")

LIKE検索、全文検索正規表現での検索には対応していない。 前方一致検索は少し工夫して、UTF-8に変換して文字コードの範囲検索する必要がある。

  • 複合インデックス whereとorderbyが異なるフィールドの場合はインデックスが必須。 なんと未作成だと実行時に下記のようなエラーメッセージが出るので、そのリンクから作成できる。
  The query requires an index. You can create it here: https://console.firebase.google.com/xxxxx
  • 複数
  db.collection("user").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        console.log(doc.id, " => ", doc.data());
    });
  }
  • カーソル
  startAt() 
  startAfter()
  endAt() 
  endBefore()

データの削除

  • ドキュメントの削除
  db.collection("user").doc("testuserid").delete()
  • フィールドの削除
  db.collection("user").doc("testuserid").update({
    age: firebase.firestore.FieldValue.delete()
  })
  • コレクションの削除 クライアントからは非推奨

トランザクション

DBの参照が必要な場合はトランザクション、不要な場合はバッチ書き込みを使う

  db.runTransaction((transaction) => {
    transaction.update(...)
  })
  • バッチ書き込み
  let batch = db.batch();
  batch.update(...)
  batch.commit()

Tips

  • getやsetの場合はawaitしよう