Maramal
Maramal

Reputation: 3465

Firebase Realtime Database How to add child with automatic ID

I am trying to make a Restful API using Firebase Realtime Database. Once I send the data from the frontend like a JSON like this:

{
    "title": "Test title",
    "description": "Another title 2",
    "author": "[email protected]",
    "steps": [
        {
            "title": "Step 1",
            "subtitle": "Step 1 subtitle",
            "inputs": [
                {
                    "inputId": "123-abc",
                    "label": "Input step 1"
                }
            ]
            
        }
    ]
}

My "issue" is that I am not sure how to add child objects to the main with a given ID like the first object.

This is how I save currently the object:

const data: any = req.body;
const ref = database.ref('/forms').push();
ref.set(data);

And then this is what is created in Firebase Realtime Database:

So, as you can see there is the main object with the ID -MNl6bPhPg6BNnM9NKEy and below, there are two sub-objects (steps & inputs) where the IDs are 0. So, my question is if there is a proper way to do this automatically or should I create the object manually and then add the childs with something like const formRef = database.ref('/forms/-MNl6bPhPg6BNnM9NKEy/');.

Any idea?

Upvotes: 1

Views: 1038

Answers (1)

Michael Bleigh
Michael Bleigh

Reputation: 26333

If I understand correctly, you want steps and inputs to be keyed using Realtime Database keys instead of numeric indices? You can always get a new automatic key through ref.push().key. So you could do something like:

function arrayToKeyedObject(arr) {
  const out = {};
  for (const val of arr) {
    out[database.ref().push().key] = val;
  }
  return out;
}

const data: any = req.body;
const ref = database.ref('/forms').push();

data.steps.forEach(step => {
  step.inputs = arrayToKeyedObject(step.inputs);
});

data.steps = arrayToKeyedObject(step.inputs);

ref.set(data);

Upvotes: 2

Related Questions