Firebase: How to extract values ​​from a snapshot object?

I'm new to Firebase, I'm having a bad time trying to extract properties from a snapshot. As in the documentation, I should be able to directly select the contents of the object this way:

snapshot.val().property_name 

However, every time I try to do this, I get an undefined value. Yes, I know that the name is correct and that the property has content.

If I do this:

 MyRoom.update({Marker1:'foo'}); MyRoom.on('child_added', function(snapshot) { alert(snapshot.name()); // it returns Marker1 alert(snapshot.val()); // it returns foo }); 

But if I try:

 MyRoom.update({Marker1:'foo'}); MyRoom.on('child_added', function(snapshot) { alert(snapshot.val().Marker1); // it returns undefined }); 

What am I doing wrong?

+5
source share
1 answer

TL; DR; you should use MyRoom.on('value', for your case.

Typically, Firebase stores two main types of data:

  • objects
  • collections

The objects

Objects that you usually save as follows:

 var MyRoom = new Firebase('your.firebaseio.com/someroom'); MyRoom.set({Name: 'This is my room', Owner: 'frank', Marker1:'bar'}); 

If you want to update / fix the object, you will do as you do it above:

 MyRoom.update({Marker1:'foo'}); 

To listen to the changes in this particular room, you use:

 MyRoom.on('value', function(snapshot) { var obj = snapshot.val(); alert(JSON.stringify(val)); // {Name: 'This is my room', Owner: 'frank', Marker1:'foo'} alert(val.Marker1); // foo }); 

Here you always get all the objects, even after you update it.

Collections

Collections are lists of objects. But the collections themselves are also objects, so you can control the collection with on('value' . But this will mean that you constantly have to deal with the entire array, which is most often not practical.

Usually you are dealing with individual entries in a collection. Firebase has special events for adding / removing / updating collections. Therefore, to listen to new items added to the collection, you do:

 var MyRooms = new Firebase('your.firebaseio.com/rooms'); MyRooms.push({Name: 'This is my room', Owner: 'frank', Marker1:'bar'}); MyRooms.on('child_added', function(snapshot) { alert(snapshot.val()); }); 

Collections are objects whose collections are objects ...

Your confusion stems from the fact that you mix the collection logic and the logic of objects from above. Although this is not often what you want, it is perfectly valid code, so it runs; just not with the result you wanted to get.

An example of how you can use "treat an object as a collection":

 var MyRoom = new Firebase('your.firebaseio.com/someroom'); MyRoom.update({Marker2:'snafu'}); MyRooms.on('child_added', function(snapshot) { // somebody added a property to MyRoom }); 

An example of when you can "treat the collection as an object": fooobar.com/questions/1201284 / ...

+6
source

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


All Articles