【问题标题】:Cloud Firestore - how retrieve document infos of nested subcollection?Cloud Firestore - 如何检索嵌套子集合的文档信息?
【发布时间】:2021-03-31 09:36:58
【问题描述】:

firestore 数据库的结构如下: 收藏:用户 id 为 user_id 的文档 每个文档都有一个子集合:游戏 每个子集合都有 id 为 game_id 的文档

我的问题是我无法遍历第一个集合 (---> for user in ref_users:) 即使我的 firestore 数据库已经充满了我所说的组织数据。有人可以帮助我了解如何检索这些文档的信息吗?非常感谢。

from flask import Flask, render_template
from google.cloud import firestore

db = firestore.Client()


@app.route('/', methods=['GET'])
def index():
    ref_users = db.collection(u'users').get()

    games = []
    for user in ref_users:
        print(f'{user.id} => {user.to_dict()}')
        ref_game = db.collection(u'users').document(f'{user.id}').collection(u'games').get()
        for rg in ref_game:
            print(f'{rg.id} => {rg.to_dict()}')
            tmp = rg.to_dict()
            tmp['game_id'] = rg.id
            tmp['user_id'] = user.id
            games.append(tmp)
    return render_template('game_list.html', title='Game list', games=games)

【问题讨论】:

  • 我不确定我是否理解这个问题。为什么不能遍历 users 集合中的文档?

标签: python google-cloud-firestore web-applications rest


【解决方案1】:

在我这边实现了这段代码,做了一些小的改动,并且运行良好。所以我认为您可能正在寻找降低计算复杂性的解决方案。 我认为collection_group 可能会有所帮助。请检查通用documentation 和 Python reference。

我为与示例相同的结果创建了代码(只是index 部分)。它少了一个循环:

def index():

    games = []
    ref_game = db.collection_group(u'games').get()
    for rg in ref_game:
        print(f'{rg.id} => {rg.to_dict()}')
        tmp = rg.to_dict()
        tmp['game_id'] = rg.id
        tmp['user_id'] = rg.reference.parent.parent.id
        games.append(tmp)
    return str(games)

我会为此子集合使用更复杂的名称,例如userGames 或其他名称。这是因为collection_group 对整个数据库中具有此名称的每个集合都有效。如果您的系统在增长,您可能会在与此逻辑无关的其他路径中使用相同的名称games。它将包含在此collection_group 中,并可能导致意外问题。

【讨论】:

  • 非常感谢,您给了我很多帮助!实际上之前已经可以工作了,但是您的代码组织得更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 2018-07-07
  • 2018-03-17
  • 2018-06-18
  • 1970-01-01
相关资源
最近更新 更多