2

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.

4

2 回答 2

4

我将在这里假设电子邮件用作对象的键而不是数组(因为您不能在 Firebase 实时数据库中拥有数组)。如果是这样的话,你可能想要这样的东西:

<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>

如果您不想实际查询电子邮件而只想插入数据,那么使用 JS SDK 也很容易:

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

对于第三个选项,您可以使用<firebase-document>路径:

<firebase-document
  app-name="my-app"
  path="/emails/[[emailKey]]"
  data="{{emailData}}">
</firebase-document>
<script>
  // ...
  this.emailKey = 'email3@example,com';
  this.emailData = {new: 'data'};
  // ...
</script>
于 2016-11-21T19:48:51.263 回答
1

据我所知,该save方法以两种方式做不同的事情:

  1. set新数据放入当前位置。
  2. push新数据放入当前位置。

为了获得push新数据,您必须提交 nokey作为方法中的第二个参数save

// This will push new data into the location /emails.
this.$.doc('/emails');

// To set new data (replacing) at location /emails.
this.$.doc('/', 'emails');

希望这对 IIRC 有所帮助。如我错了请纠正我。

于 2016-11-21T16:28:32.740 回答