Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new key value pair to existing Firebase

This might be a pretty basic question, but so far I can't find the answer to my problem online after much googling. I have a firebase web app where the data structure is pretty simple. Initially, it's empty, like this:

fireRef {
}

I want to be able to add key value pairs where the key is created by the user and the value is just some text. For instance, the user would enter their name as the key, and the value as their age. Then I want to send that data to the server and have the firebase now look like this:

fireRef {
    John : 25,
}

I can accomplish this one addition with:

var name = getUserName();
var age = getUserAge();
var node = {};
node[name] = age;
fireRef.set(node);

However, I want multiple people to be able to do this. When I try to add a new person to the server, the old "John : 25" pair turns red and disappears, leaving only the new key value pair.

How can I keep both around, and maintain a dataset of a bunch of key, value pairs?

like image 762
Nick Avatar asked May 02 '15 01:05

Nick


2 Answers

The unique id in firebase is generated when we push data.

For example:

var fireRef = new Firebase('https://<CHANGE_APP_NAME>.firebaseio.com/fireRef');
var newUserRef = fireRef.push();
newUserRef.set({ 'name': 'fred', 'age': '32' });

Another way is to directly set the child elements:

var fireRef = new Firebase('https://<CHANGE_APP_NAME>.firebaseio.com/fireRef');
fireRef.child(1).set({'name':'user2','age':'34'});
fireRef.child(2).set({'name':'user3','age':'24'});
like image 156
bprasanna Avatar answered Nov 19 '22 00:11

bprasanna


@user3749797, I got confused with this exact problem.

@learningloop offered a good solution, because it achieves the task of adding data to your firebase, but there is an option to add a new k,v (name, age) pair into a single JSON associative array rather than push to an array of associative arrays. Effectively, @learningloop sees:

[
    { 
        name: steve, 
        age: 34 
    }, 
    { 
        name: mary, 
        age: 22 
    }
]

Perhaps his way is better, but you and I were looking for this:

    { 
        steve: 34, 
        mary: 22 
    }

I've managed to add to this list of k,v pairs with

    var fireRef = new Firebase('https://<CHANGE_APP_NAME>.firebaseio.com/fireRef');
    fireRef.update({ 'jobe': '33'});

Yielding

    { 
        steve: 34, 
        mary: 22, 
        jobe: 33 
    }

In my firebase.

Full documentation on saving to firebase [here]

like image 6
Charlie Avatar answered Nov 19 '22 00:11

Charlie