Search code examples
javascriptfirebaseupdating

Doing Firebase Update that Adds a Child


I'm trying to add a child node during an update. Best by example:

name: 'mike'
      address: '123 main street'

name: 'paul'
      address: '1189 second avenue'

name: 'ethyl'
      address: '22 appletree lane'
      pet_count: 3

So, "mike" goes off and gets a dog at the shelter, so I have to add his pet if he doesn't have any or increment the count if he does have one. The desired results are:

name: 'mike'
      address: '123 main street'
      pet_count: 1

name: 'paul'
      address: '1189 second avenue'

name: 'ethyl'
      address: '22 appletree lane'
      pet_count: 3

Now, if I add another pet to mike's fast-growing herd, I get...

name: 'mike'
      address: '123 main street'
      pet_count: 1

name: 'paul'
      address: '1189 second avenue'

name: 'ethyl'
      address: '22 appletree lane'
      pet_count: 3

I understand the incrementing of the count is application-specific and I'm ok with that. I'm just not seeing how to add that pet_count node if none is present. Any language is fine. Javascript seems neutral if you want to answer in code.

I've tried things like:

nameRef.child('mike').set({address: '123 main street',
                           pet_count: 1});

and it fires the changed event but I can't see that on the Forge. I don't think the data is persisted.

I've also tried:

nameRef.update({name: 'mike', {address: '123 main street',
                           pet_count: 1});

Those last two should have been equivalent, right?

Any hints what I'm missing here?


Solution

  • What are you getting in Firebase for pet count after doing the things you've tried? I can't tell from your question if the pet_count is showing up as 1 or if it's not showing up at all in firebase. It looks like you're setting the pet_count to 1 every time. Not sure what your increment counter looks like but instead of doing pet_count: 1, set it to the value of your counter, pet_count: Counter Value

    nameRef.child('mike').set({name: 'mike', {address: '123 main street',
                           pet_count: CounterValue});
    

    I don't know if update creates a new key if it doesn't exist.