Update or install Firebase

After adding a post about a person to the Firebase database, I want to add a link to a new post for a person. However, man may or may not 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, this creates a node called _person in the child person, instead of the value of the _person variable. Using set () will overwrite the existing person.

Example: First, the remark node / -JlkbxAKpQs50W7r84gf is created with the child element node person / 123456

After that, I want to create node person / 123456 (only if it does not already exist) and add the child node note / -JlkbxAKpQs50W7r84gf to it. After-identifier is automatically generated (Firebase), but the identifier of the person should be taken from the html form.

How to do it?

+5
source share
1 answer

Depending on the structure of your data, you may get a link to the person you want before update .

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 link:

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

Then you want to know if it exists, and if so, update it:

 personRef.once('value', function(snapshot) { if( snapshot.val() === null ) { /* does not exist */ } else { snapshot.ref().update({"postID": postID}); } }); 
+9
source

Source: https://habr.com/ru/post/1216556/


All Articles