16

im using the firestore library from google.cloud, is there any way to check if a document exists without retrieven all the data? i tried

fs.document("path/to/document").get().exists()

but it returns a 404 error. (google.api_core.exceptions.NotFound)

then i tried

fs.document("path/to/document").exists()

but "exists" isn't a function from DocumentReference.

I can see from the source that exists() is a function from the DocumentSnapshot Class, and the function get() should return a documentSnapshot. i'm not very sure how else i can get a DocumentSnapshot

Thank you

  • I have this same problem, on firebase admin v 2.14.0, where `db.collection('...').document('...').get()` throws `google.api_core.exceptions.NotFound: 404` when the doc doesn't exist. It's very strange, this seems to be a recent problem on my server and works fine on my macbook install (where `....get().exists` returns False with no exception) – patricksurry Dec 12 '18 at 17:41

4 Answers4

18

A much simpler and memory efficient approach:

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

Source

Cloudkollektiv
  • 11,852
  • 3
  • 44
  • 71
7

If you're using firebase-admin:

fs.collection('items').document('item-id').get().exists

True iff items/item-id exists.

Alternatively

'item-id' in (d.id for d in fs.collection('items').get())
avishayp
  • 706
  • 5
  • 9
2

Try this:

docRef      = db.collection('collectionName').document('documentID')
docSnapshot = docRef.get([]); # Empty array for fields to get
isExists    = docSnapshot.exists

With this approach, you will retrieve an empty document. You will incur cost of 'reading', but there will be reduced network egress and almost zero change in in-use memory of the process.

Amit
  • 21
  • 2
-1

You have to retrieve the document in order to know if it exists or not. If the document exists, it will count as a read.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 3
    Oh, an official answer from a Firebase insider... Thanks for the concise answer, but wouldn't it be a useful feature to know if a document exists without knowing its contents? :o – varun May 04 '19 at 07:28