swift - 添加孩子时的Firebase,另一个孩子被删除
问题描述
我正在尝试向名为“users_want_notification”的孩子添加一个孩子。这似乎可行,但是当我尝试将第二个孩子添加到名为“users_want_notification”的孩子中时,第一个孩子将被删除。我怎样才能改变这个,所以第一个孩子不会被删除?
我的代码:
Database.database().reference()
.child("Notification").child("users").child(username)
.setValue(["username": username, "url": Foto_url])
Database.database().reference()
.child("Notification").child("users").child(username)
.child("users_want_notification").child(Pro_user)
.setValue(["Pro_user": Pro_user, "toDeviceID": AppDelegate.DEVICEID])
火力基地:
解决方案
当您调用setValue
子节点时,该节点下的所有现有数据都将替换为您传递给的值setValue
。如果我们查看您的第一个电话:
Database.database().reference()
.child("Notification").child("users").child(username)
.setValue(["username": username, "url": Foto_url])
这将替换 下的所有现有数据/Notification/users/$username
,包括其users_want_notification
子节点下的所有数据。由于您随后在 下添加了一个新的子节点users_want_notification
,看起来该调用替换了现有的子节点,但实际上它是第一个setValue
删除所有数据的调用。你可以通过暂时注释掉第二个调用来测试它,你会看到整个users_want_notification
消失了。
您有两个主要选择:
对个体和属性使用单独
setValue
的调用:username
url
let userRef = Database.database().reference() .child("Notification").child("users").child(username) userRef.child("username").setValue(username) userRef.child("url").setValue(Foto_url]) userRef.child("users_want_notification").child(Pro_user) .setValue(["Pro_user": Pro_user, "toDeviceID": AppDelegate.DEVICEID])
由于现在所有
setValue
调用都发生在低于 的级别/Notification/users/$username
,因此永远不会替换整个节点。
推荐阅读
- scala - 输出时间戳列值在 Scala Spark 中的写入操作期间发生变化?
- node.js - 如何跟踪 AWS CloudWatch Log Stream 日志?
- sql - 连接表选择仅存在于一个表中的值
- stored-procedures - 我正在寻找通过 SQL Workbench/J 上的宏运行变量列表
- google-apps-script - 如何检索 Javascript HTML 文件中的变量,然后将其映射到 code.gs 函数
- sql - 在 CASE 语句 TSQL 中赋值会出错
- python - Pandas:在 +/- 特定日期内合并两个数据框的 id 和匹配日期范围
- java - Java:KMeans Spark 将集群中心加入预测数据框
- typescript - 如何使用所有对象键创建类型化数组?
- json - 容器上日期控制器的自定义验证逻辑