When getting the document by the key and this document is not found, Firestore returns the Document not found error on the Console. Is there a way to avoid this being thrown as an error or to treat this in code, since try/except doesn't do the trick?
There are a few ways to handle the Document not found
error in Firestore.
1. Use the get()
method and check the exists
property of the returned DocumentSnapshot
object.
import firebase_admin
from firebase_admin import firestore
db = firestore.client()
doc_ref = db.collection('users').document('user_id')
doc_snapshot = doc_ref.get()
if doc_snapshot.exists:
# The document exists.
print(doc_snapshot.to_dict())
else:
# The document does not exist.
print('Document not found.')
on_snapshot()
method to listen for changes to a document and handle the case where the document does not exist when the callback function is first called.
import firebase_admin
from firebase_admin import firestore
db = firestore.client()
doc_ref = db.collection('users').document('user_id')
def on_snapshot(doc_snapshot, changes, error):
if error:
# An error occurred.
print(error)
elif doc_snapshot.exists:
# The document exists.
print(doc_snapshot.to_dict())
else:
# The document does not exist.
print('Document not found.')
doc_ref.on_snapshot(on_snapshot)
3. Use the transaction()
method to ensure that your code does not fail if the document does not exist.
import firebase_admin
from firebase_admin import firestore
db = firestore.client()
def transaction(transaction):
doc_ref = db.collection('users').document('user_id')
doc_snapshot = transaction.get(doc_ref)
if not doc_snapshot.exists:
# The document does not exist.
# Create the document with the default data.
transaction.set(doc_ref, {})
# Update the document data.
transaction.update(doc_ref, {'name': 'New name'})
db.run_transaction(transaction)
Which method you use depends on your specific needs. If you need to check if the document exists before accessing its data, use the get()
method and check the exists
property of the returned DocumentSnapshot
object. If you need to listen for changes to the document and handle the case where the document does not exist, use the on_snapshot()
method. If you need to ensure that your code does not fail if the document does not exist, use the transaction()
method.
I am using the doc.exists on the code, but the code 5 error (Document not found) is still showing in the logs of my application. The intention is just to retrieve the document, so no set is needed.
The code is like this:
document = (
firestore_client.collection(COLLECTION_NAME)
.document(key)
.get(transaction=transaction)
)
if document.exists:
return document.to_dict()
return None
So the error is coming from Firestore directly. Do you know if there is a way to not have this error on Console logs?
import firebase_admin
from firebase_admin import firestore
# Import the Firebase Admin SDK and the Firestore client library.
# How to handle the "Document not found" error in Firestore
# Use a try/except block to catch the Document not found error
try:
db = firestore.client()
doc_ref = db.collection("users").document("user_id")
document = doc_ref.get()
if document.exists:
# The document exists
print(document.to_dict())
else:
# The document does not exist
print("Document not found")
except firestore.errors.NotFoundError:
# Handle the error here, e.g., log a custom message or ignore
print("Document not found")
# This approach will prevent the error from being logged to the console and is the most straightforward method for handling the "Document not found" scenario.
# Use the on_snapshot() method
doc_ref = db.collection("users").document("user_id")
def on_snapshot(doc_snapshot, changes, error):
if error:
# An error occurred
print(error)
elif doc_snapshot.exists:
# The document exists
print(doc_snapshot.to_dict())
else:
# The document does not exist
print("Document not found")
doc_ref.on_snapshot(on_snapshot)
# This method listens for changes to a document and will not return an error if the document does not exist. However, it's best suited for real-time updates and might be overkill for a simple document existence check.
# Use the transaction() method
def transaction(transaction):
doc_ref = db.collection("users").document("user_id")
doc_snapshot = transaction.get(doc_ref)
if not doc_snapshot.exists:
# The document does not exist
print("Document not found")
# If you want to create a new document, uncomment the line below.
# transaction.set(doc_ref, {})
else:
# Update the document data
transaction.update(doc_ref, {"name": "New name"})
db.run_transaction(transaction)
# This method allows you to perform a series of read and write operations on Firestore data in a single atomic operation. If any of the operations fail, the entire transaction is rolled back. However, be cautious when using this method to avoid introducing unnecessary behavior, such as creating new documents unintentionally.
# Use code with caution
NotFoundError
exception and handle it appropriately.on_snapshot()
method:This method listens for changes to a document, and will call a callback function whenever the document changes or is deleted.You can use this callback function to handle the case where the document doesn't exist when the callback function is first called.transaction()
method:This method allows you to perform a series of read and write operations on Firestore data in a single atomic operation. If any of the operations fail, the entire transaction is rolled back. You can use this method to ensure that your code does not fail if the document doesn't exist.Which approach you use depends on your specific needs. If you need to check if the document exists before accessing its data, use the try/except block or the on_snapshot()
method. If you need to ensure that your code does not fail if the document doesn't exist, use the transaction()
method.