Reputation: 57
I am trying to reference a variable that I am storing the users UID to in a document reference to Cloud Firestore. The path doesn't seem to read a string though. I have tried two different way and both ways give me errors. How would you pass a variable string into a Cloud Firestore document/collection path?
I am getting the UsernameID from the database with:
UsernameID = Auth.auth().currentUser!.uid
var UsernameID = String()
let ref = db.collection("user/\(UsernameID)/account").document("created")
ref.getDocument { (document, error) in
if let document = document, document.exists {
print("User Exists")
} else {
print("User does not exist in firestore")
}
}
Throws error:
*** Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Invalid path (user//account). Paths must not contain // in them.'
libc++abi.dylib: terminating with uncaught exception of type NSException
var UsernameID = String()
let ref = db.collection("user").document(UsernameID).collection("account").document("created")
ref.getDocument { (document, error) in
if let document = document, document.exists {
print("User Exists")
} else {
print("User does not exist in firestore")
}
}
Throws error:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FIRESTORE INTERNAL ASSERTION FAILED: Invalid document reference. Document references must have an even number of segments, but user has 1'
I have also tried storing the uid as a DocumentReferce but it failed to store a string as a DocumentReference.
let UsernameID = DocumentReference!
Upvotes: 2
Views: 3915
Reputation: 118
In your top example
db.collection("user/\(UsernameID)/account")
It seems that you are not requesting your user collection. This is why you are getting the error about \ in collection names. The user collection should be something like this
let ref = db.collection("user").document(UsernameID)
ref.getDocument { (document, error) in
if let document = document, document.exists {
print("User Exists")
} else {
print("User does not exist in firestore")
}
}
The .document should get the user document corresponding to the UsernameID passed. To get at a property you would need to access it via the document variable.
Upvotes: 0
Reputation: 35657
Assuming you are authenticating correctly, here's what you want to do to access a document stored in Firestore. Suppose the structure is
users //collection
uid //document
name //field within the document
and the code to read the name field
let uid = Auth.auth().currentUser?.uid
let collectionRef = self.db.collection("users")
let userDoc = collectionRef.document(uid)
userDoc.getDocument(completion: { document, error in
if let err = error {
print(err.localizedDescription) //document did not exist
return
}
if let doc = document {
let name = doc.get("name")
print(name)
}
})
Upvotes: 1