4

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

1 Answer 1

10

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);
Sign up to request clarification or add additional context in comments.

1 Comment

so in short there is no way to make multiple push in one go then ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.