2023-07-09 中高生のためのChatGPTのFirestoreのデータを集計したい

ローカルスクリプトでFirestoreのデータを読む

データを読もうとしたが読めなかった

ルールを変更しても読めなかった

  • 具体的なメッセージを1件取得するコードを作ったらできた
  • でも db.collection('users').get()したがsnapshot.sizeはゼロ

もう一度考えて「サービスアカウントに普通のユーザと同じアクセス権を付与してもユーザの一覧取得はできないじゃん」と気づいた

  • nishio.iconsnapshot.size is zero. I just noticed that the rule deny traversal. Fix it
  • GPT-4.iconallow list: if request.auth.token.firebase.sign_in_provider == "null";

それでもダメ、末端のオブジェクトを取得できるのに親をトラバーサルできない現象がなぜ起こるのか理由を聞いた

  • GPT-4.iconNo user document: When you fetch a nested sub-collection document directly (as in code A), Firestore doesn’t need the parent document to exist. In other words, even if there’s no document at users/{userId}, you can still fetch a document at users/{userId}/rooms/{roomId}/messages/{messageId}.
  • Firebase コンソールでの Cloud Firestore の管理
  • 祖先が存在しない場合であっても、ドキュメントは存在できます。

  • これか…

祖先ドキュメントが存在しない時に子孫ドキュメントを列挙するには?

  • nishio.icon How to get all /users/<user_id>/rooms/<room_id> when /users/<user_id> is not exists.
  • gpt-4.icon There is a way to fetch all rooms from all users using a Firestore feature called Collection Group Queries.
    • db.collectionGroup('rooms').get()
    • できた

そのroomがどのユーザに属しているかはどうやって知る?

  • nishio.iconGiven doc, how can I see its parent <user_id>
  • gpt-4.icon doc.ref.parent.parent.id

後は集計するだけ!めでたしめでたし!