简体   繁体   中英

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?

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

    }

Yes.. I got the point..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM