如何使用Polymer Fire向Firebase中插入数据(多节点+多路径)

How to insert data into Firebase using Polymerfire (mutiple nodes + multiple paths)

我的用例是我有一个 <iron-form> 和一个 <paper-textarea> 字段,该字段接受我解析为数组的电子邮件地址的字符串列表,然后我想:

  1. 将个人电子邮件地址存储在我的 Firebase 中(用于索引和查找目的),
  2. 在多个位置(根据 数据扇出 技术),
  3. 使用单个写入操作(因为如果列表那么长,我不想进行 100 API 次调用)并且
  4. 不覆盖任何现有数据。

具体来说,我想先从状态A说起,如下:

状态A
my-app
 |
 - emails
 |  |
 |  - email1@example,com
 |     |- old: "data"
 |  - email2@example,com
 |     |- old: "data"
 - users
    |
    - c0djhbQi6vc4YMB-fDgJ

并实现状态B如下:

B国
my-app
 |
 - emails
 |  |
 |  - email1@example,com
 |     |- old: "data"
 |  - email2@example,com
 |     |- old: "data"
 |  - email3@example,com
 |     |- new: "data"
 |  - email4@example,com
 |     |- new: "data"
 - users
    |
    - c0djhbQi6vc4YMB-fDgJ
       |
       - emails
          |
          - email3@example,com
             |- new: "data"
          - email4@example,com
             |- new: "data"

注意:{old: "data"}不会被覆盖。

背景

.

在那里,我们使用三个选项在新位置插入了一个节点:

  1. 使用firebase-query
  2. JS SDK
  3. 使用firebase-document

现在,我需要为多个节点(使用用户定义的而非自动生成的密钥;即密钥是特定的电子邮件地址)执行相同类型的插入(不删除或替换旧数据)。我还需要使用数据扇出技术通过单个写入操作更新多个路径。

Similar to what's shown here.

https://firebase.google.com/docs/database/web/read-and-write#update_specific_fields
function writeNewPost(uid, username, picture, title, body) {
  // A post entry.
  var postData = {
    author: username,
    uid: uid,
    body: body,
    title: title,
    starCount: 0,
    authorPic: picture
  };

  // Get a key for a new Post.
  var newPostKey = firebase.database().ref().child('posts').push().key;
  // * * * * * * * * * * * * * * * *  
  // THE ABOVE LINE NEEDS TO CHANGE TO SUPPORT USER-GENERATED KEYS SUCH AS EMAIL ADDRESSES
  // * * * * * * * * * * * * * * * * 

  // Write the new post's data simultaneously in the posts list and the user's post list.
  var updates = {};
  updates['/posts/' + newPostKey] = postData;
  updates['/user-posts/' + uid + '/' + newPostKey] = postData;

  return firebase.database().ref().update(updates);
}

另请注意,其中一条评论提到:

There's no reason newPostKey above couldn't be an email address...

挑战在于我需要在一次调用中同时将多个密钥写入多个位置。

Firebase 实时数据库支持任意复杂的原子深度更新 (blog post)。它是这样工作的:

  1. 您可以通过一次 .update() 调用
  2. 更新任意深度的路径
  3. 更新映射键侧的完整路径将被替换,因此如果您不想破坏父键,您必须直接处理子键
  4. 路径是相对于您当前的 ref

让我们举个例子:

var update = {};

update['emails/email3@example,com'] = {new: 'data'};
update['emails/email4@example,com'] = {new: 'data'};
update['users/c0djhbQi6vc4YMB-fDgJ/emails/email3@example,com'] = {new: 'data'};
update['users/c0djhbQi6vc4YMB-fDgJ/emails/email4@example,com'] = {new: 'data'};

firebase.database().ref().update(update);

这将同时更新所有位置。要使其动态化,只需在构造键时使用字符串插值即可。