Firebase使用对象数组推送到数据库

时间:2016-07-15 16:55:55

标签: node.js firebase firebase-realtime-database

firebase数据库推送方法使用唯一键向数据库子项添加对象,例如

postsRef.push({
  author: "gracehop",
  title: "Announcing COBOL, a New Programming Language"
});

在数据库中添加如下内容

"posts": {
    "-JRHTHaIs-jNPLXOQivY": {
      "author": "gracehop",
      "title": "Announcing COBOL, a New Programming Language"
    }

但是,如果我将push方法与对象数组一起使用,例如

    postsRef.push({
        {
          author: "gracehop1",
          title: "Announcing COBOL, a New Programming Language"
        },
        {
          author: "gracehop2",
          title: "Announcing COBOL, a New Programming Language"
        }});

我在数据库中得到一个带有枚举对象的唯一键,即

"posts": {
    "-JRHTHaIs-jNPLXOQivY": {
      "0": { 
         "author": "gracehop1",
         "title": "Announcing COBOL, a New Programming Language"
       },
      "1": {
         "author": "gracehop2",
         "title": "Announcing COBOL, a New Programming Language"
       }
     }}

有没有办法在单个事务中push一个对象数组,这样我就可以为数组中的每个对象获取一个唯一的键,即结果看起来像

"posts": {
        "-JRHTHaIs-jNPLXOQivY": {
             "author": "gracehop1",
             "title": "Announcing COBOL, a New Programming Language"
         "-JRHTHaIs-jNPLXOQivZ": {
             "author": "gracehop2",
             "title": "Announcing COBOL, a New Programming Language"
           }
         }}

1 个答案:

答案 0 :(得分:7)

一个鲜为人知的事实是,您可以在没有任何参数的情况下调用push(),它只会为您生成位置/推送ID。通过该位置和多位置更新(请参阅herehere),您可以执行以下操作:

var key1 = postsRef.push().key;
var key2 = postsRef.push().key;
var updates = {};
updates[key1] = {
      author: "gracehop1",
      title: "Announcing COBOL, a New Programming Language"
    };
updates[key2] = {
      author: "gracehop2",
      title: "Announcing COBOL, a New Programming Language"
    };
ref.update(updates);