Michel
Michel

Reputation: 11755

Flattening data with Firebase

After reading the documentation here: https://www.firebase.com/docs/ios/guide/structuring-data.html

I am working on flattening my data. Here is the issue I am facing at the moment, in the code below:

    let firebaseDBNameUnit = ["titleString": "name1"],
    firebaseNameRef = topRef.childByAppendingPath("MyApp/Name")
    firebaseNameRef.childByAutoId().setValue(firebaseDBNameUnit) // *
    let firebaseDBContentUnit = ["contentString": "very long content 1 11 111 1111 etc... blah blah blah"],
    firebaseContentRef = topRef.childByAppendingPath("MyApp/Content")
    // The following line is where my question is:
    firebaseContentRef.childByAutoId().setValue(firebaseDBContentUnit)

I would like to change the last line in the code above, to use an ID which is the same as the one produced in the line marked *. How can I do that?

In order to create a relationship between Name and Content, I could of course create a field of my own, but it would be so much better to use the ID already provided by Firebase.

Upvotes: 0

Views: 190

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600131

When you call childByAutoId() it returns a reference to the new location. If you capture that in a variable, you can use it:

let unitRef = firebaseNameRef.childByAutoId()
unitRef.setValue(firebaseDBNameUnit) 

...

firebaseContentRef.childByAppendingPath(unitRef.key).setValue(firebaseDBContentUnit)

Upvotes: 1

Related Questions