0

I would be grateful that you can help me with the following:

I have an Ionic 2 project, and need to know how to save objects with custom keys in Firebase database.

Actually, in Firebase I have:

+ blabla
+ blabla
- users : 
    - UIDXXX : {
        + last_audio: {}
        + sessions : []
    }

Well, instead the string UIDXXX, I need to save the user's uid as key, for example:

- users : 
          - 232ssadas223ss2 : {
                  + last_audio: {}
                  + sessions : []
            }
          - das112dasd21dsd : {
                  + last_audio: {}
                  + sessions : []
            }

           .
           .
           .

This is how I'm retrieving data actually:

this.auth.subscribe((user) => {
    if (user) {
        let firebaseObservable = this.angularFire.database.object(`/users`);
        firebaseObservable.update({
            useruid : {
                last_audio: this.audio,
                sessions: [
                    "Hoy",
                    "Ayer"
                ]
             }
        });
    }
});

But, obviously I'm saving the word "userid" as key instead the user.uid, and in Firebase I'm getting:

users :
- useruid : {
    + last_audio: {}
    + sessions : []
}

Thank you very much in advance.

AL.
  • 36,815
  • 10
  • 142
  • 281
Ivan Lencina
  • 1,787
  • 1
  • 14
  • 25

1 Answers1

1

You can set the data into the object with so-called bracket notation:

    let firebaseObservable = this.angularFire.database.object(`/users`);
    var updates = {};
    updates[userid] = {
            last_audio: this.audio,
            sessions: {
                "Hoy": true,
                "Ayer": true
            }
         };
    firebaseObservable.update(updates);

I also changed your sessions array to a set, since it likely better reflects what you're storing. For some more on arrays vs sets, see my answer here: Firebase query if child of child contains a value

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I love you, you saved my day! It works! I did not know about this. If there is a problem, I will consult you if it is not a problem, thank you! :) – Ivan Lencina Feb 07 '17 at 00:00
  • Actually, within sessions I should save dates, I just put strings to test and forget to correct it. Sessions will actually save data like "2017-06-02", "2017-05-02" instead of "Hoy", "Ayer". I clarify for the correction you made me, is it a good idea to do so in this context? – Ivan Lencina Feb 07 '17 at 00:08