0

How do I check if a Google Firebase Firestore document exists?

I've tried the following code in my project:

let db = Firestore.firestore() let UserName = UserNameText.text print(UserName!) let userRef = db.collection("users").document(UserName!) print("one") userRef.getDocument { (document, error) in print("two") if let document = document { print("three") if document.exists{ print("Document data: \(String(describing: document.data()))") } else { print("Document does not exist") } } } 

Here is a picture of my data on firebase.google.com: Click here

The print(UserName!) will return the correct value. The following code will output one and two but will stop there.

2
  • Use if let document = document, document.exists {. Check out the example here: firebase.google.com/docs/firestore/query-data/… Commented Apr 9, 2018 at 22:13
  • If it does not print 3, then perhaps, you are returning an error. Print out the error variable also. Commented Apr 9, 2018 at 22:14

1 Answer 1

1

@JRLtechwriting solved my problem.

"Use if let document = document, document.exists {. Check out the example here: https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document"

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.