collectionGroupとは
違うコレクションでも同じ名前のサブコレクションを持つドキュメントを一括でデータを取得出来る。
例えば構図が、
user(コレクション)
docId
items(サブコレクション)
item_name:"item1"
name:"hoge"
age:20
admin(コレクション)
docId
items(サブコレクション)
item_name:"item2"
name:"hogehoge"
age:30
だった時、collectionGroupを用いることで、userコレクションのitemサブコレクションも、adminコレクションのitemサブコレクションも同時に取得できる。
[sample.vue]
await this.$fire.firestore
.collectionGroup("items")
.get()
.then((docs)=>{
docs.forEach((doc)=>{
console.log(doc.get("item_name")); //item1とitem2が出力される
})
})
.where()や.orderBy()を使った複合クエリも可能。
親のドキュメントデータを取得
取得したdocを
doc.ref.parent.parent
で参照することで親のdocを取得できる。
[sample.vue]
await this.$fire.firestore
.collectionGroup("items")
.get()
.then((docs) => {
docs.forEach((doc) => {
const parentRef = doc.ref.parent.parent; //親のdocを参照
parentRef.get().then((parentDoc) => {
console.log(doc.id); //itemサブコレクションのdocId
console.log(parentRef.id); //親のdocId
console.log(doc.get("item_name")); //itemサブコレクションのitem_nameフィールド
console.log(parentDoc.get("name")); //親のdocのnameフィールド、
});
});
});