きっかけ
firestoreを使って開発していますが、
- CollectionReferenceとかQuerySnapshotとか種類多すぎてわからん…
- get()とかdata()は何に呼び出されて、何返すんだっけ?
と思うことがよくあり、その都度API documentを参照しています。
この時間がもったいないなと思ったので、すぐにわかるようまとめておきます。
同じ思いをしている誰かのためになればと思います🙏
前提
Nuxt.jsでfireAuthから呼び出す前提とします。
javascript
await this.$fireStore.collection(`/users/${userId}/items`).get()
この記事で出てくる型の種類
- Firestore
- CollectionReference
- DocumentReference
- DocumentSnapshot
- Query
- QuerySnapshot
- QueryDocumenSnapshot
型ごとによく使うメソッドと返り値
- 1. Firestore
- doc()
- DocumentReferenceをかえす
- ex)
this.$fireStore.doc('LA')
- collection()
- CollectionReferenceをかえす
- ex)
this.$fireStore.collection('cities')
- doc()
- 2. CollectionReference
- id
- Stringをかえす(コレクションのID)
- ex)
this.$fireStore.collection('cities').id
- doc()
- DocumentReferenceをかえす
- ex)
this.$fireStore.collection('cities').doc('LA')
- get()
-
Promise<QuerySnapshot>
をかえす - ex)
await this.$fireStore.collection('cities').get()
-
- where()
- Queryをかえす
- ex)
this.$fireStore.collection('cities').where(townId, 'in', townIds)
- orderBy()
- Queryをかえす
- ex)
this.$fireStore.collection('cities').orderBy('createdAt', 'desc')
- id
- 3. DocumentReference
- id
- Stringをかえす(ドキュメントのID)
- ex)
this.$fireStore.collection('cities').doc('LA').id
- get()
-
Promise<DocumentSnapshot>
をかえす - ex)
await this.$fireStore.doc('LA').get()
-
- set()
-
Promise<void>
をかえす - ex)
await this.$fireStore.doc('LA').set({ ... })
-
- delete()
-
Promise<void>
をかえす - ex)
await this.$fireStore.doc('LA').delete()
-
- collection()
- CollectionReferenceをかえす
- ex)
this.$fireStore.doc('LA').collection('towns')
- id
- 4. DocumentSnapshot
- ref
- DocumentReferenceをかえす
- ex)
this.$fireStore.collection('cities').where(townId, 'in', townIds).ref
- get()
- anyをかえす
- ex)
this.$fireStore.collection('cities').where(townId, 'in', townIds).get('townName')
- data()
- T or undefinedをかえす(Tはオブジェクト、自分で型を指定する)
- ドキュメント内のすべてのフィールドを返す
- ex)
this.$fireStore.collection('cities').where(townId, 'in', townIds).data()
- ref
- 5. Query
- get()
-
Promise<DocumentSnapshot>
をかえす - ex)
await this.$fireStore.collection('cities').where(townId, 'in', townIds).get()
-
- get()
- 6. QuerySnapshot
- docs
-
Array<QueryDocumentSnapshot>
をかえす - ex)
this.$fireStore.collection('cities').get().docs
-
- forEach()
- voidをかえす(処理を実行するだけ)
- ex)
this.$fireStore.collection('cities').get().docs.forEach(doc => {...})
- docs
- 7. QueryDocumentSnapshot
- id
- Stringをかえす(そのドキュメントのID)
- ex)
this.$fireStore.collection('cities').get().docs.map(doc => { doc.id })
- ref
- DocumentReferenceをかえす
- ex)
this.$fireStore.collection('cities').get().docs.map(doc => { doc.ref })
- get()
- anyをかえす
- ex)
this.$fireStore.collection('cities').get().docs.map(doc => { doc.get('townId') })
- data()
- T or undefinedをかえす(Tはオブジェクト、自分で型を指定する)
- ドキュメント内のすべてのフィールドを返す
- ex)
this.$fireStore.collection('cities').get().docs.map(doc => { doc.data() })
- id
https://firebase.google.com/docs/reference/js/firebase.firestore.QueryDocumentSnapshot
ねがい
これでだいぶ楽になるといいな…🙏