Cloud Firestore更新文档触发无限循环问题求助
解决Cloud Firestore更新文档时的无限循环问题
嘿,我一眼就找到你代码里的问题啦!你之所以第二次调用会陷入无限循环,核心原因是用了实时监听addSnapshotListener,同时在监听回调里又修改了文档——当你第一次更新文档后,Firestore会触发实时监听的回调,而回调里又会执行更新操作,这样就形成了"更新→触发监听→再更新→再触发监听"的死循环,不管用.update()还是.set()都会触发这个问题,因为这两个操作都会修改文档内容,触发实时监听的回调。
最简单的解决方案:替换成一次性数据获取
你的需求是找到对应的用户文档并更新,根本不需要持续监听集合的变化。把addSnapshotListener换成getDocuments()就可以解决问题,因为getDocuments()只会一次性获取当前的数据,不会在文档变化时重复触发回调。
修改后的代码如下:
func modifyInfoOwner(info: UserInfo){ let fireStoreDB = Firestore.firestore() var documentID = "" // 用getDocuments()替代实时监听,仅一次性获取数据 fireStoreDB.collection("Users").whereField("email", isEqualTo: info.email).getDocuments { (snapshot, error) in if error != nil { print(error?.localizedDescription) } else { guard let snapshot = snapshot, !snapshot.isEmpty else { print("未找到匹配的用户文档") return } // 邮箱应该是唯一的,直接取第一个文档即可,不用循环 if let targetDocument = snapshot.documents.first { print("| saving info in DB") print("v") print(info) documentID = targetDocument.documentID fireStoreDB.collection("Users").document(documentID).setData([ "adress" : info.adress, "name" : info.name, "phone" : info.phoneNumber, "seatQuantity" : info.seatQuantity, "email" : info.email, "token" : info.token ]) { error in if let error = error { print("Data could not be saved: \(error).") } else { print("Data saved successfully!") } } } } } }
额外优化建议
因为用户的邮箱通常是唯一标识,所以不需要循环遍历所有匹配的文档,直接取snapshot.documents.first就能定位到目标文档,既避免了不必要的循环,也防止多个相同邮箱的用户导致重复更新。
内容的提问来源于stack exchange,提问作者Nicolas Lucchetta
相关产品推荐
相关产品推荐

