Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase update or set

After adding a post about a person to a Firebase database, I want to add the reference to the new post to the person. However the person may or may not already exist.

I have:

var ref = new Firebase("https://mydatabase.firebaseio.com/");
var _person = document.getElementById("Person").value;
var _remark = document.getElementById("Remark").value;

var postsRef = ref.child("remarks");
var newPostRef = postsRef.push({
    person: _person,
    remark: _remark
});

var postID = newPostRef.key();

var personRef = ref.child("person");
personRef.update({
    _person: postID
});

However that creates a node called _person in child person instead of the value of the _person variable. Using set() would overwrite an existing person.

Example: First a node remarks/-JlkbxAKpQs50W7r84gf is created with child node person/123456

After that I want to create a node person/123456 (only if it doesn't already exist) and than add a child node remark/-JlkbxAKpQs50W7r84gf to it. The post-id is automatically generated (Firebase) but the person's id is to be taken from a html form.

How do I do that?

like image 648
user1837293 Avatar asked Mar 31 '15 16:03

user1837293


1 Answers

Depending on how your data is structured, before you update, you may be able to get a reference to the person you want.

So, if your data looks something like this:

{
    "remarks" : {
                   ...
                },

    "person" : {
                 "123456" : {
                                "name" : "foo",
                                ...
                                "blah" : "bar"
                            },
                 ...
               }
}

And document.getElementById("Person").value gives you 123456, you can get the reference like:

var personRef = ref.child("person").child(_person);

Then you want to see if it exists, and if it does, update it:

personRef.once('value', function(snapshot) {

    if( snapshot.val() === null ) {
        /* does not exist */
    } else {
        snapshot.ref.update({"postID": postID});
    }

});
like image 120
Seamus Avatar answered Sep 21 '22 06:09

Seamus