如何在Python中将文档ID添加到Firestore文档

Jm3*_*m3s 1 python firebase google-cloud-firestore

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

我已经打印了ID,并说它应该是相同的。虽然在消防局中有所不同。

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,
            })
Run Code Online (Sandbox Code Playgroud)

例如,文档的ID为:“ aMqwOsjDbOuQmi8PZmot”,但“ property_id”值显示为:“ YU1xd09zak ...”。有人知道为什么会发生这种情况吗?

在此处输入图片说明

Ale*_*amo 5

发生这种情况是因为您生成了两次随机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
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,您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
Run Code Online (Sandbox Code Playgroud)

然后在代码中进一步使用该docId变量,而不是 doc_ref.id每次调用该变量时都不会生成另一个id 的变量。