首页 > 解决方案 > How to push a child into Firebase RealTime Database with a specified key?

问题描述

I'm developing an app using React Native and Firebase RealTime database.

I want to do the following. I want to create a data tree like following.

myRoot
  |
  |---myKey: "myValue"

But here, I DON'T want to do it as follows.

foo = async () => {
   let myRef = firebase.database().ref('myRoot');

   await myRef.set({
      myKey: "myValue"
   })
}

Instead, I want to do something like this.

writeData = async (key, value) => {
   let myRef = firebase.database().ref('myRoot');

   await myRef.set({
      key: value
   })
}

And, then call the function to add data.

this.writeData(myKey, myValue);

For example, after I called the function as below,

this.writeData("myFirstKey", "myFirstValue");
this.writeData("mySecondKey", "mySecondValue");
this.writeData("myThirdKey", "myThirdValue");

I need the output as below.

myRoot
  |
  |---myFirstKey: "myFirstValue"
  |---mySecondKey: "mySecondValue"
  |---myThirdKey: "myThirdValue"

How to do this?

标签: javascriptfirebasereact-nativefirebase-realtime-database

解决方案


Calling set on a given object will replace it completely instead of set you can use update function like this

writeData = async (key, value) => {
 let myRef = firebase.database().ref('myRoot');
   await myRef.update({
     key:value
    })

    }

推荐阅读