0

I'm trying to retrieve JSON data from my firebase data from a constantly updated child. The snapshot key changed on every new data submission. (using sparkpost to send data to firebase). I am trying to figure out a way to structure my retrieval so that it will fetch from the most recent key.

var ref = new Firebase("https://watspark.firebaseio.com/raw-events/");
var _url = ('https://watspark.firebaseio.com/raw-events/');


// Retrieve new posts as they are added to our database
ref.on("child_added", function(snapshot, prevChildKey) {
  var newPost = snapshot.val();
  console.log(snapshot.val());

  // console.log("text: "  + newPost.text);
  // console.log("Title: " + newPost.title);
  // console.log("Previous Post ID: " + prevChildKey);
  // var fireUrl = ("https://watspark.firebaseio.com/raw-events/" + snapshot.val() + "/0/msys/relay_message/content");
  //  var bigBoy = new Firebase(fireUrl);
  //   console.log("text: " + bigBoy.text);

  var param = snapshot.key();
  console.log(param);
});

ref.orderByChild("0/mysys/relay_message/content/text").on("child_added",   function(snapshot) {
  console.log(snapshot.key() + "was" + snapshot.val().text);
});

my JSON data is structured like this:

   snapshot.val();
   {
     0 {
       mysys{
         relay_message{
           content

How would I go about doing this? Thanks

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39
bretth18
  • 53
  • 1
  • 2
  • 8
  • 1
    It depends on your definition of "the most recent". When you're querying a list that is populated with push ids, you can get the latest with `ref.orderByKey().limitToLast(1)`. But note that this will work fine for short lists, but will get slower and slower as the list grows (see [this](http://stackoverflow.com/questions/34482615/database-i-o-capacity-in-firebase-usage-metrics-analytics-tab/34482768#34482768) and [this](http://stackoverflow.com/q/35165815/)). If you only care about the latest item, it's better to keep a `latestItemKey: "-Khasdgsagd" and update that for every new item you add. – Frank van Puffelen Feb 14 '16 at 17:49
  • right, but I still am having a hard time passing the latest item key into the firebase URL so that I can retrieve my text fields 3 levels into my json data – bretth18 Feb 14 '16 at 18:03

1 Answers1

0

I was able to do call the most recent child by doing this:

ref.orderByKey().limitToLast(1).on("child_added", function(snapshot) {
  var child = snapshot.val();
  console.log(snapshot.key());
  var snapKey = '' + snapshot.key();

  snapshot.child("0/msys/relay_message/content/").forEach(function(snap){
    console.log('snap ' + snap.val());
    if(snap.key() === 'text'){
      watsonInput = snap.val();
    }
  });

  snapshot.child("0/msys/relay_message/").forEach(function(snap){
    console.log('email: ' + snap.val());
    if(snap.key() === 'msg_from'){
      email = snap.val();
    }
    //call to remove current snapshotKey
  });
bretth18
  • 53
  • 1
  • 2
  • 8