0

Is there a way to update the database with a dynamic id as a key?

Let's say I want the database to look like this:

- Data
     - dynamic key
         - data 1
         - data 2

This key is supposed to grow every time databaseRef.updateChildValues(addObject) is being called.

Further more, is there a way to set a var as a key? I've tried this but it didn't work:

var addId: Int = 0

func updateData() {
        ...

        addId += 1

        let addObject = [
            addId: someData
            ] as [String: Any]

        databaseRef.updateChildValues(addObject)
    }
Tom
  • 3,672
  • 6
  • 20
  • 52
  • Possible duplicate of [How to get the push() key generated my Firebase?](https://stackoverflow.com/questions/49547325/how-to-get-the-push-key-generated-my-firebase) – cutiko May 04 '19 at 17:34

2 Answers2

0

You may need childByAutoId()

let value:[String:Any] = ["key":"value"]
ref.child("Data").childByAutoId().setValue(value)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

The key doesn't grow. It's a key.

You can add additional child nodes under that key if that's what you mean but updateChild values will only add additional nodes if the node doesn't exist. Otherwise it will update that node.

Also, if you want to get a key to a new node you can do this

let childOfDataRef = your_fb.child("data").childByAutoId()
let key = childOfDataRef.key
Jay
  • 34,438
  • 18
  • 52
  • 81