Nick Pineda
Nick Pineda

Reputation: 6462

Firebase: Create New Object With Push and Then Push to it Simultaneously

Tools: Vanilla Firebase and Vanilla JavaScript

So I'm creating a new convo and adding it's first message in one go.

convos:{
    uniqueConvoID1:{
        uniqueMessage:{
          text:"Hi Gus"
        },
        ...
    },
    ...
}

But because both need a unique Id I essentially need to do two pushes simultaneously.One creates the new object (like uniqueConvoID1), and then creates a new message inside like (uniqueMessageId).

I've tried creating an empty object first and then pushing the message but I don't think creating an empty object first is valid.

Question: How do I then initialize an object within an object where both objects need a unique key?

What I tried:(I pushed a new message and got the convo back.)

var newConvoIDRef =  firebaseConvosRef.push({
    authorName: 'Nick',
    text:"Hey!How you been?",
    timestamp: Date.now() - 99999
 });

Which created this in the Dashboard:

-convos
     - -K2111111111111111 //unique convo id
         -authorName:"Nick"
         -text:"Hey! How have you been?"
         -timestamp:1446866141625

But what I need to initial the new convo this way:

 -convos
     - -K2111111111111111 unique convo id
         - -K222444444444444 unique message id
             -authorName:"Nick"
             -text:"Hey! How have you been?"
             -timestamp:1446866141625

Upvotes: 0

Views: 606

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

I think you're seriously overcomplicating things. Firebase creates paths automatically as you add new values. So this will create the entire chain:

var convosRef = new Firebase('https://yours.firebaseio.com/convos');
var convRef = convosRef.push();
var msgRef = convRef.push();

msgRef.set({
    authorName: 'Nick',
    text:"Hey!How you been?",
    timestamp: Date.now() - 99999
 });

Note: Firebase also cleans paths up automatically when all values under them are removed. So you can remove the entire branch of the tree, by:

msgRef.remove();

Upvotes: 1

Related Questions