我正在尝试在将用户UID存储到Cloud Firestore的文档引用中引用一个变量。路径似乎没有读取字符串。我尝试了两种不同的方式,两种方式都给我带来错误。您如何将变量字符串传递到Cloud Firestore文档/集合路径?
我从数据库中获得用户名ID:
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")
}
}
抛出错误:
*** 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")
}
}
抛出错误:
*** 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'
我也曾尝试将uid存储为DocumentReferce,但未能将字符串存储为DocumentReference。
let UsernameID = DocumentReference!
答案 0 :(得分:1)
假设您正确进行身份验证,这是您要访问存储在Firestore中的文档的操作。假设结构是
users //collection
uid //document
name //field within the document
和用于读取名称字段的代码
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)
}
})
答案 1 :(得分:0)
在您的最佳示例中
db.collection("user/\(UsernameID)/account")
似乎您不是在请求用户集合。这就是为什么在集合名称中出现有关\的错误的原因。用户集合应该是这样的
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")
}
}
.document应该获取与传递的UsernameID相对应的用户文档。要获得属性,您需要通过document变量进行访问。