【问题标题】:How to add document ID to the firestore document in Python如何在 Python 中将文档 ID 添加到 Firestore 文档
【发布时间】:2019-02-16 13:43:15
【问题描述】:

我正在尝试使用 python 将 firestore 上的新文档的文档 ID 添加到对象本身中,但是在添加时它会缩短字符串并且实际上并没有添加相同的 ID。

我已经打印了 ID,它说应该是一样的。虽然在 Firestore 中有所不同。

doc_ref = db.collection(u'prime_location').document()
        print('ID: ', doc_ref.id)
        docId = doc_ref.id

         # set object and push to firebase
        doc_ref.set({
                u'property_id': docId,
                u'property_address': address,
                u'number_of_beds': number_beds,
                u'number_of_baths': number_baths,
                u'property_rent': property_price,
                u'post_code': postcode,
                u'property_photo': property_image,
            })

这方面的一个例子是文档的 id 是:'aMqwOsjDbOuQmi8PZmot' 但 'property_id' 的值是:'YU1xd09zak...' 有人知道为什么会发生这种行为吗?

【问题讨论】:

    标签: python firebase google-cloud-firestore


    【解决方案1】:

    发生这种情况是因为您生成了两次随机 id。

    doc_ref = db.collection(u'prime_location').document()
            print('ID: ', doc_ref.id) //generates one id
            docId = doc_ref.id //generates the second id
    

    要解决这个问题,您可以通过只调用一次 doc_ref.id 来生成一个 id,如下面的代码行所示:

    doc_ref = db.collection(u'prime_location').document()
            docId = doc_ref.id //generates id
            print('ID: ', docId) //print the generatd id
    

    然后在您的代码中进一步使用 docId 变量和 not doc_ref.id 每次调用都会生成另一个 id。

    【讨论】:

      猜你喜欢
      • 2018-07-22
      • 2020-12-04
      • 2019-06-15
      • 2018-12-05
      • 1970-01-01
      • 2020-01-05
      • 2022-01-21
      • 1970-01-01
      • 2018-07-10
      相关资源
      最近更新 更多