Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  62] [ 3]  / answers: 1 / hits: 20643  / 9 Years ago, tue, march 31, 2015, 12:00:00

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?


More From » firebase

 Answers
7

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

});

[#67242] Saturday, March 28, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hailie

Total Points: 25
Total Questions: 112
Total Answers: 111

Location: Belize
Member since Tue, Dec 8, 2020
3 Years ago
hailie questions
;