Firebase,iOS:将键值对附加到子节点

Firebase,iOS: Appending key-value pair into a child node

我在 Firebase

中有以下用户 Table 结构

正如您在我打开的用户中看到的那样,我有一个帖子部分,在这个 post 部分中包含 ID 已被该用户 post 编辑的所有文章。

我遇到的问题如下:

当用户创建一篇新文章时,它会保存在帖子 Table 中,保存后我 return 新生成的 ID 然后传递给用户 table,我试图将新创建的 ID 插入用户的 post 部分,所以我假设 URL 是这样的:

Users/{UserId}/Posts 

然而,所有这一切都创建了一个名为 posts 的新部分,它实际上并没有将记录插入给定区域。

我的无效代码如下:

let linkPost = [childautoID: true]

FIRDatabase.database().reference().child("Users/\(UserId)/Posts").child(UserId).setValue(linkPost)

仅供参考,目前在我手动添加的帖子中的两个 ID。

我还尝试了以下方法:

FIRDatabase.database().reference().child("Users/\(UserId)/Posts").setValue(linkPost)

然而,所有这一切都会删除所有现有的 ID,然后插入新的 ID。

要在 Firebase 数据库子节点中附加键值对,请使用:-

  • 对当前用户的 Posts 节点进行 Firebase 数据库引用 FIRDatabase.database().reference().child("Users").child(FIRAuth.auth()!.currentUser!.uid).child("Posts")

  • 检查 Posts 节点是否存在于您的用户数据库中,如果不存在,则通过以下方式创建一个:- parentRef.setValue([postId : "True"]) in else块.

  • 但如果 Posts 节点确实存在,将其检索为 NSMutableDictionary ,将新对象设置为它,然后存储该节点的更新字典。


  func storePostsToDB(postID :String!, userID : String! = FIRAuth.auth()!.currentUser!.uid){

    let parentRef = FIRDatabase.database().reference().child("Users").child(userID).child("Posts")
    parentRef.observeSingleEventOfType(.Value, withBlock: {(friendsList) in

        if friendsList.exists(){
             if let listDict = friendsList.value as? NSMutableDictionary{

                    listDict.setObject("True", forKey: postID)
                    parentRef.setValue(listDict)

                }
        }else{
            parentRef.setValue([postID : "True"])
        }
    })
  }

调用函数:-

  storePostsToDB("yourPostID")// If you want to store in the currentUser DB
  storePostsToDB("yourPostID", userID : otherUserID)//If you want to store the post in some other users database with uid `otherUserID`

我更喜欢这样的东西。这会自动附加数据而不先获取

FIRDatabase.database().reference().child("Users/\(UserId)/Posts").child(UserId).setValue(true)