简体   繁体   中英

How to add values to a key using Firebase?

This is some code I have to initialize Firebase:

firebase.initializeApp(config);
var database = firebase.database();
var ref = database.ref('names');
var data = {
  userName: Elbert
}
ref.push(data);

Although I understand how to retrieve a unique key, I don't know how to push new data to that unique key. Specifically, I'm trying to add a child to the unique key under userName. I'd appreciate any help, thanks!

image of data tree

I assume when you say that you would like to add a child to the unique key you mean along side rather than under userName as userName is a value itself, eg adding an email such as:

  names
    -L2Btcm5y1Nm0mCXi-E_
        userName: Elbert
        email: some@email.com

To do this you can either set the full data value under the unique key, ie:

var ref = database.ref('names/-L2Btcm5y1Nm0mCXi-E_');
var data = {
  userName: 'Elbert',
  email: 'some@email.com'
};
ref.set(data);

Or you can get a reference directly to the key you would like to set, ie:

var ref = database.ref('names/-L2Btcm5y1Nm0mCXi-E_/email');
ref.set('some@email.com');

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