Ad

How To Add The Same ChildByAutoID Under Multiple Structures In Firebase Using Swift?

To create a new value, I use...

Database.database().reference().child("checklists").childByAutoId().setValue(["title":title,"imageUrl":imageUrl])

How can I take that .childByAutoId value created and set it under another structure like below?

enter image description here

I manually created the value using...

Database.database().reference().child("users").child(uid).child("checklists").childByAutoId().setValue(["listID":"-Lm21a-rDc6qBPcfpVUw"])

How can I do it automatically?

Ad

Answer

When you call childByAutoId() it returns a DatabaseReference to the new location. On that reference you can either write a value, or for example get its key. With the latter you can then write the same key in another location (either as the key of a node, or its value).

So something like:

let ref = Database.database().reference().child("checklists").childByAutoId()
ref.setValue(["title":title,"imageUrl":imageUrl])

Database.database().reference().child("users").child(uid).child("checklists")
                               .childByAutoId().setValue(["listID":ref.key])

You can also use that key, in case you want another node with the same key:

Database.database().reference().child("users").child(uid).child("checklists")
                               .child(ref.key).setValue("yay!")
Ad
source: stackoverflow.com
Ad