Home > Software design >  Is there any way to specify the auto-generated key that firebase makes when you push an object to th
Is there any way to specify the auto-generated key that firebase makes when you push an object to th

Time:10-24

I am trying to push something to the firebase rtdb and I would like to access it elsewhere pretty easily. This is what I am using to add to the rtdb:

function addStudentHandler(studentData) {
        fetch(
            "url that I put in real code",
            {
                method: "POST",
                body: JSON.stringify(studentData),
                headers: {
                    "Content-Type": "application/json",
                }
            }
        )
        .then (() => {
            history.replace("/");
        });
    }

Is there like a title value or some other kind of value to specify it instead of having auto-generated unique keys? I appreciate any responses.

CodePudding user response:

It is your own code that tells Firebase to generate a unique key, because you are using the POST method. As specified in the documentation on saving data:

POST: Add to a list of data in our Firebase database. Every time we send a POST request, the Firebase client generates a unique key, like fireblog/users/<unique-id>/<data>

If you want to specify the complete path yourself, you can use PUT which is documented as:

PUT Write or replace data to a defined path, like fireblog/users/user1/<data>.

So when you specify PUT, you specify the entire path to write to, Firebase won't generate a unique ID under the path, and will simply write the value you specify to the path you specify.


In your existing code:

fetch(
    "url that I put in real code/user1.json", //            
  • Related