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
an 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"
}
}}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With