firebasefirebase-realtime-databasepolymerpolymerfire

Push data to Firebase via polymerfire/firebase-query element


I'm a little stuck trying to push data on demand to a Firebase database using the polymerfire polymer element. I have a data binding inside a DOM element and it works flawlessly for registers that already exists. My real question is how to create new registers with unique id?

//firebase query for a specific path and a data binding
<firebase-query
   id="query"
   app-name="testApp"
   path="/[[uid]]/messages"
   data="{{data}}">
</firebase-query>

//dom repeat for each item inside the data binding
<template is="dom-repeat" items="{{data}}">
   <div class="card">
      <p>[[item.text]]</p>
   </div>
</template>

If I modify the template to have an iron-input and a 2 way data binding, this update the register at ease and no problem in Firebase.

<template is="dom-repeat" items="{{data}}">
   <div class="card">
      <input is="iron-input" bind-value="{{item.text}}">
   </div>
</template>

The real tricky part is how to push a new object (message) to Firebase with a unique id, something like "lasdjlkadj1978kld"?

//firebase estructure
{
   "uid" : {
      "messages" : {
         "message1" : {
            "message" : "some text",
            "timestamp" : "some date"
         },
         "message2" : {
            "message" : "some text",
            "timestamp" : "some date"
         }
         ...
         ...
      }
   }
}

I have tried updating the "data" object via JS but its only modified locally...


Solution

  • I'm not sure I understand your question correctly.

    How to create new registers with unique id?

    You can use firebase-document that provide save method that take 2 arguments parentPath and key (just leave the key).

    <firebase-document id='document'
      data='{{data}}'>
    </firebase-document>
    
    <script>
      Polymer({
        saveMessage: function () {
          // path = /<uid>/messages in your case
          this.$.document.save(path).then(function () {
            // after document saved, path will be changed to the new ref
            // any change of data will sent back up and stored
          });
        }
      });
    </script>
    

    I had tried updating the "data" object via js but its only modified locally...

    How you update the data, Did you use this.set?