我正在尝试使用以下代码读取子集合中的文档数,但这正在读取子集合中文档数倍的文档数,我想确保只读取一次很多次文件,请协助,谢谢
func getNumberOfComments() {
Firestore.firestore().collection("posts").document(postId).collection("comments").getDocuments{ (snapshot, error) in
if let error = error{
print (error.localizedDescription)
} else {
if let snapshot = snapshot{
for document in snapshot.documents{
let data = document.data()
self.length = snapshot.count
print("counting " , self.length!)
// var length2 = data.count
// print ("printing ", length2)
}
}
}
}
}
答案 0 :(得分:3)
这正在读取的文档数量是子集合中文档的数量
发生这种情况是因为以下代码行:
self.length = snapshot.count
print("counting " , self.length!)
每次迭代都被调用。如果只想打印一次,则只需在for循环开始之前将它们移到循环中即可,以使上述代码行脱离循环:
func getNumberOfComments() {
Firestore.firestore().collection("posts").document(postId).collection("comments").getDocuments{ (snapshot, error) in
if let error = error{
print (error.localizedDescription)
} else {
if let snapshot = snapshot{
self.length = snapshot.count
print("counting " , self.length!)
for document in snapshot.documents{
let data = document.data()
}
}
}
}
}