简体   繁体   中英

Firebase updating nested data without deleting

For some reason, calling updateChildren on my database is erasing all data currently located there. The JSON tree looks like this

{
  "user1" : {
    "messages" : {
      "-message1" : true
    },
    "userId" : "value"
  }
}

I'm attempting to insert message 2 under message 1, however, all it does is replaces message 1 with message 2

fun addToCurrentUser() {
    val user = Firebase.auth.currentUser
    val id = user?.uid
    val map: MutableMap<String, Any> = HashMap()
    map.put(message.getId(), true)
    root.child("users/" + id + "/messages/").updateChildren(map)
}

If you want to add new data at a known location, you can just use setValue() on the path directly, disregarding anything else in the path.

root
    .child("users")
    .child(id)
    .child("messages")
    .child(message.getId())
    .seValue(true)

If you target any node for an update, everything under that location will be replace, so it's better to target as deep as possible to make the required change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM