LoginSignup
90
78

More than 1 year has passed since last update.

コピペで使うFirebase【Cloud Firestore編】

Last updated at Posted at 2019-10-03

概要

firestoreを使う際にコピペで動かしたいのでそのまとめです。

公式ドキュメント

Cloud Firestore
初期設定
データの追加
データの取得
クエリー
リアルタイム更新

FireStoreのメソッド一覧
メソッド 動作 備考
add 追加 ドキュメント名はランダムな文字列になる
set 追加 ドキュメント名を指定できる
set 更新 ドキュメントを更新(上書き)、フィールド追加
update 更新 ドキュメントのフィールドを更新
get 取得 ドキュメントを取得
delete 削除 ドキュメントを削除
onSnapshot 取得 変更の監視・データ取得

応用

初期設定

インストール

$ npm install firebase --save

firestore初期化

import firebase from "firebase/app"
import "firebase/firestore"

const firebaseConfig = {
    /* firebase config */
}

// 初期化は一度だけ
if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig);
}

firestore参照

const db = firebase.firestore();

ドキュメント追加

add

add() はドキュメント名にランダムなid(文字列)が入る。

db.collection("user").add({ name: "taro" }).then(docRef => {
    // success
}).catch(error => {
    // error
})

保存されたデータ

user: {
    <ランダムなid>: {
        name: taro
    }
}

set

set() はドキュメント名を指定できる。

※ doc() を引数なしで使うとadd()と同じくドキュメント名にランダムなid(文字列)が入る。

db.collection("user").doc("1").set({ name: "taro" }).then(docRef => {
    // success
}).catch(error => {
    // error
})

保存されたデータ

user: {
    1: {
        name: taro
    }
}

ドキュメントの更新

update

update() はdoc()に指定したドキュメントのフィールドを更新する

※更新するフィールドがない場合はエラーとなる

db.collection("user").doc("1").update({ name: "taro san" }).then(() => {
    // success
}).catch(error => {
    // error
})

更新前

user: {
    1: {
        name: taro
    }
}

更新後

user: {
    1: {
        name: taro san
    }
}

set

set() を使うと対象のドキュメント自体を更新します

db.collection("user").doc("1").set({ firstName: "taro", lastName: "aso" }).then(() => {
    // success
}).catch(error => {
    // error
})

更新前

user: {
    1: {
        name: "taro"
    }
}

更新後

user: {
    1: {
        firstName: "taro",
        lastName: "aso"
    }
}

mergeオプション

set() ではmergeオプションをつけるとフィールドの追加もできます

db.collection("user").doc("1").set({ firstName: "taro", lastName: "aso" }, {merge: true}).then(() => {
    // success
}).catch(error => {
    // error
})

更新前

user: {
    1: {
        name: "taro"
    }
}

更新後

user: {
    1: {
        name: "taro",
        firstName: "taro",
        lastName: "aso"
    }
}

ドキュメントの取得

get

get() はドキュメントを取得します。

Firestoreには以下のデータが保存されているとします

user: {
    1: {
        name: "taro"
    },
    2: {
        name: "ken"
    }
}

コレクション内の全てのドキュメントを取得する場合

/* 全てのドキュメントを配列に代入 */
const users = [];
db.collection("user").get().then((docs) => {
    // success
    if (docs.exists) {
        docs.fotEach(doc => {
            users.push(doc.data())
        })
    }
    console.log(users)
}).catch(error => {
    // error
})

取得データ

[{ name: "taro" }, { name: "ken" }] // type Array(2)

指定のドキュメントを取得する場合

db.collection("user").get("2").then((doc) => {
    // success
    console.log(doc.data())
}).catch(error => {
    // error
})

取得データ

{ name: "ken" }

where

指定のフィールドでフィルタリングしドキュメントを取得する場合

db.collection("user").where('name', '==' 'taro').get().then((docs) => {
    // success
    console.log(doc.data())
}).catch(error => {
    // error
})

取得データ

{ name: "taro" }

ドキュメントの削除

delete

delete() は対象のドキュメントを削除します。

db.collection("user").doc("1").delete().then(() => {
    // success
}).catch(error => {
    // error
})

リアルタイム更新

onSnapshot

onSnapshot() は対象のドキュメントまたはコレクション内の複数のドキュメントの更新を検知しデータを取得します。

// ドキュメント
db.collection("user").doc("1").onSnapshot((doc) => {
    // doc => 対象のドキュメント
}, (error) => {
    // ...
})

// コレクション
db.collection("user").onSnapshot((docs) => {
    // docs => コレクション内の複数のドキュメント
}, (error) => {
    // ...
})

応用

ドキュメント名をidフィールドにももたせる場合

db.collection("user").add({ id: "", name: "taro" }).then(docRef => {
    db.collection("user").doc(docRef.id).update({
        id: docRef.id
    }).then(() => {
        // success
    }).catch(error => {
    // error
    })
}).catch(error => {
    // error
})

保存されたデータ

user: {
    <ランダムなid>: {
        id: <ランダムなid>
        name: taro
    }
}

前方一致検索

const word = "ke"
db
  .collection("user")
  .orderBy('name')
  .startAt(word)
  .endAt(word + '\uf8ff')
  .get()
  .then((docs) => {
    // success
  }).catch(error => {
    // error
  })

取得データ

[{ name: "ken" }, { name: "kenta" }]

範囲期間内のもの

日付はfirebase.firestore.Timestamp型である必要がある

const startDate = new Date(1992, 5, 1)
const startDate = new Date(2000, 6, 1)
db
  .collection("user")
  .orderBy('birthdate', 'desc')
  .where('birthdate', '>=', startDate)
  .where('birthdate', '<=', endDate)
  .get()
  .then((docs) => {
    // success
  }).catch(error => {
    // error
  })

取得データ

[{ name: "ken" }]

メモ

2021/07/26 随時更新中
追加予定
- 排他処理(同時更新制御)
- バッチ処理

90
78
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
90
78