2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

collectionGroupで親のドキュメントデータを取得する

Posted at

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フィールド、
       });
     });
   });
2
1
0

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?