在 Firestore 中存储字典值时的逻辑问题

Posted

技术标签:

【中文标题】在 Firestore 中存储字典值时的逻辑问题【英文标题】:Problem with logic when it comes to storing dictionary values in firestore 【发布时间】:2019-07-09 06:15:11 【问题描述】:

我正在尝试重新创建 instagram 关注者和关注功能,但逻辑上似乎存在错误。代码没有错误。当按下“关注”按钮时,我现在正在做的是创建一个名为“用户关注”的集合,将“当前 UID”添加为“文档 ID”,然后将以下目标用户数据存储为 [targetuid: 1]。同时,我创建了一个名为“用户关注者”的集合,将“目标 UID”添加为“文档 ID”,然后将关注者数据存储为 [currentuid:1]。这里的问题是它在只关注一个用户时有效。当我尝试关注另一个用户时,现有的关注用户数据会被我刚刚关注的新用户覆盖,而不是附加数据。

示例:假设 currentUser 为 A,user1 = B,user2 = C 当我关注 user1 和 user2 时,我在 firestore 中的数据库应反映为:

user-following -> A -> [B:1,C:1]
user-followers -> B -> [A:1]
user-followers -> C -> [A:1]

以上转换为集合 -> documentID -> dictionaryvalues 问题是我没有得到上述结果。相反,当我关注 user2 时,user1 的值会被覆盖。所以只存储了一个字典值。

我知道问题出在我尝试在文档 ID 下创建字段的方式上。我知道我可以创建一个字典并附加值,但我认为对于其他简单的解决方案来说,这是很多代码。

func follow()
        guard let currentUid = Auth.auth().currentUser?.uid else 
         return
        guard let uid = uid else return
        self.isFollowed = true

        // Add followed user to current user-following structure
        Firestore.firestore().collection("user- 
         following").document(currentUid).setData([uid:1])

        // Add current user to followed user-follower structure
        Firestore.firestore().collection("user- 
         followers").document(uid).setData([currentUid:1])
        

【问题讨论】:

【参考方案1】:

没关系。意识到我必须使用合并。

Firestore.firestore().collection("user- 
         following").document(currentUid).setData([uid:1], merge: true)

【讨论】:

以上是关于在 Firestore 中存储字典值时的逻辑问题的主要内容,如果未能解决你的问题,请参考以下文章

更改 nsdictionary 中的布尔值时的 EXC_BAD_ACCESS

比较 C 中链表中的值时的问题

golang 从 map 获取值时的值拷贝问题

循环浏览字典时的 Discord Py bot 垃圾邮件通道

Flutter 如何优化 Firestore 存储读取以防止大量不必要的读取

如何将从firebase存储上传的图像保存到firestore数据库中的currentUser