James B James B - 4 months ago 67
Node.js Question

Firebase Push to Database with Array of Objects

The firebase database push method adds an object to the database child with a unique key, e.g.,

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


puts something like the following in the database

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


However, if I use the push method with an array of objects, e.g.

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


I get a single unique key with enumerated objects in the database, i.e.,

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


Is there any way to
push
and array of objects in a single transaction such that i get a unique key for each object in the array, i.e., a result that looks something like

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

Answer

A little known fact is that you can call push() without any arguments and it will just generate a location/push id for you. With that and multi-location updates (see here and here), you can do:

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