firebasefirebase-realtime-databasepolymer-1.0firebase-polymerpolymerfire

Polymer 1.x + Firebase 2.x: How to push or put data to Firebase using Polymerfire?


Using Polymerfire, I want to add new nodes to a Firebase without overwriting data. (I call this push or put behavior.)

In other words. I want to start with this:

State A
my-app
 |
 - emails
    |
    + email1@example,com
    + email2@example,com

And finish with this.

State B
my-app
 |
 - emails
    |
    + email1@example,com
    + email2@example,com
    + email3@example,com
    + email4@example,com

But when I start with State A and do this:

<firebase-document
    id="doc"
    app-name="app"
    data="{{data}}">
</firebase-document>
...
this.$.doc.save('/', 'emails');

I wind up with this:

State B
my-app
 |
 - emails
    |
    + email3@example,com
    + email4@example,com

Notice the starting data: email1@example,com and email2@example,com were deleted.

Here is the Polymerfire documentation. But it doesn't mention anywhere how to accomplish this type of push or put-type method to insert data into a node.

How can I accomplish this?

Edit

The answer by @motss suggests:

this.$.doc('/emails');

instead of

this.$.doc('/', 'emails');

But that does not work because it adds a random auto key as follows:

State B
my-app
 |
 - emails
    |
    - -hvOxpxwjpWHBYGj-Pzqw
       |
       + email3@example,com
       + email4@example,com

Note the added key: -hvOxpxwjpWHBYGj-Pzqw thereby destroys the indexing feature of the data structure.


Solution

  • I'm going to assume here that the emails are used as keys for objects and are not an array (since you can't have arrays in a Firebase Realtime Database). If that's the case, you probably want something like:

    <firebase-query
      id="emails"
      app-name="my-app"
      path="/emails"
      data="{{emails}}">
    </firebase-query>
    <script>
      // ...
      this.$.emails.ref.child('email3@example,com').set({new: 'data'});
      // ...
    </script>
    

    If you don't want to actually query the emails but just want to insert data, that's easy as well using the JS SDK:

    firebase.database().ref('emails').child('email3@example,com').set({new: 'data'});
    

    For a third option, you can use <firebase-document> with a path:

    <firebase-document
      app-name="my-app"
      path="/emails/[[emailKey]]"
      data="{{emailData}}">
    </firebase-document>
    <script>
      // ...
      this.emailKey = 'email3@example,com';
      this.emailData = {new: 'data'};
      // ...
    </script>