Firestore覆盖iOS Swift中已存在的数据
HoDYPGk4wvhrlgvA3bRYPAromE22当前已登录用户。 在firestore db我有追随者和下面的表。 如果当前用户点击下面的按钮,则会在下表中写入 – 当前用户是文档ID,然后是用布尔值为true的用户ID。
这是下表的截图。
当用户点击下面的按钮时,我的问题是覆盖id后面的6wP1l0yBDDQA146NqNBBzFEgX4u2。 它没有添加新ID。
这是我试过的代码:
self.db.collection("followers").document(id).setData([API.User.CURRENT_USER!.uid: true]) self.db.collection("following").document(API.User.CURRENT_USER!.uid).setData([id: true])
如果给出merge:在setData之后的true,如setDfata([id:true],merge:true),它表示方法重载参数。
我试过这样但不太合作:
func followAction(withUser id: String) { print("withuser:::\(id)") let docRef = db.collection("user-posts").document(id) print("id::::\(docRef)") docRef.getDocument { (document, error) in if let document = document, document.exists { self.db.collection("followers").document(id).setData([API.User.CURRENT_USER!.uid: true]) self.db.collection("following").document(API.User.CURRENT_USER!.uid).setData([id: true]) let dataDescription = document.data().map(String.init(describing:)) ?? "nil" print("Document data: \(dataDescription)") self.db.collection("feed").document(API.User.CURRENT_USER!.uid).setData([document.documentID: true]) } else { print("Document does not exist") self.db.collection("followers").document(id).updateData([API.User.CURRENT_USER!.uid: true]) self.db.collection("following").document(API.User.CURRENT_USER!.uid).updateData([id: true]) } } // self.db.collection("followers").document(id).setData([API.User.CURRENT_USER!.uid: true]) // self.db.collection("following").document(API.User.CURRENT_USER!.uid).setData([id: true]) // self.db.collection("following").document(API.User.CURRENT_USER!.uid).setData([id: true]) // REF_FOLLOWERS.child(id).child(Api.User.CURRENT_USER!.uid).setValue(true) // REF_FOLLOWING.child(Api.User.CURRENT_USER!.uid).child(id).setValue(true) }
通常我会在这里使用自动递增键。 Following -> AutoKey -> ["followedBy": userId1, followedTo: userId2]
因为Firestore支持查询,您可以通过这些查询轻松过滤用户跟随的用户。 但根据注释和您当前的数据库结构,您需要在更新之前获取以前的数据,否则它将替换旧数据。 见下面的例子:
let followingRef = Firestore.firestore().collection("Following").document("HoDYPGk4wvhrlgvA3bRYPAromE22") followingRef.getDocument { (snapshot, error) in guard let _snapshot = snapshot else {return} if !_snapshot.exists { /// First time following someone followingRef.setData(["6wP1l0yBDDQA146NqNBBzFEgX4u2": true]) return } // For next time var data = _snapshot.data() data["6wP1l0yBDDQA146NqNBBzFEgX4u2"] = true followingRef.setData(data) }