如何知道firestore python中是否存在文档?

Cri*_*zúa 9 python-3.x google-cloud-firestore

我正在使用 google.cloud 的 firestore 库,有没有办法在不检索所有数据的情况下检查文档是否存在?我试过

fs.document("path/to/document").get().exists()
Run Code Online (Sandbox Code Playgroud)

但它返回 404 错误。(google.api_core.exceptions.NotFound)

然后我试过了

fs.document("path/to/document").exists()
Run Code Online (Sandbox Code Playgroud)

但“存在”不是来自 DocumentReference 的函数。

从源代码可以看出,exists() 是 DocumentSnapshot 类中的一个函数,函数 get() 应该返回一个 documentSnapshot。我不太确定我还能如何获得 DocumentSnapshot

谢谢

Neb*_*tic 10

一种更简单且内存高效的方法:

doc_ref = db.collection('my_collection').document('my_document')
doc = doc_ref.get()
if doc.exists:
    logging.info("Found")
else:
    logging.info("Not found")
Run Code Online (Sandbox Code Playgroud)

来源


avi*_*ayp 7

如果您正在使用firebase-admin

fs.collection('items').document('item-id').get().exists
Run Code Online (Sandbox Code Playgroud)

True当且仅当items/item-id存在。

或者

'item-id' in (d.id for d in fs.collection('items').get())
Run Code Online (Sandbox Code Playgroud)