rahul singhania rahul singhania - 1 month ago 22
Javascript Question

Getting nested data from firebase database by "onchildchanged" and "onchildadded" returns something unrecognizable

console_screenshot

This is the screenshot of the console that displays the output i.e. the child added in the messages directory of one of the users.


Also , it must be noticed that I have displayed very short portion of console, as the console is displaying similar output for each and every messages. If more screenshots are required for clarification, please tell me, I will add them!


This is my json code:

{
"Tf42glUiUvbF1yGMX1CseYD6EVC3" : {
"intents" : {
"intentFields" : "",
"intentName" : ""
},
"messages" : {
"-KViVgc7ZG051eMXP0-5" : {
"name" : "Ed",
"photoUrl" : "https://cdn1.iconfinder.com/data/icons/user-pictures/100/male3-512.png",
"text" : "Hello, I'm Ed, your personal assistant cum friend",
"timeStamp" : "1476880306"
},
"-KW3C8azYBP_-BIlWmNV" : {
"name" : "Aakash Bansal",
"photoUrl" : "https://lh5.googleusercontent.com/-oQyA4HXVycc/AAAAAAAAAAI/AAAAAAAAHKo/Ov0A0p0LjiY/s96-c/photo.jpg",
"text" : "hi", //this is the message displayed in the console above.
"timeStamp" : "1478613047"
}
}
},
"gFiPrpHcHeMkqG2tGUi1aolIR3x1" : {
"intents" : {
"intentFields" : "",
"intentName" : ""
},
"messages" : {
"-KViVgc7ZG051eMXP0-5" : {
"name" : "Ed",
"photoUrl" : "https://cdn1.iconfinder.com/data/icons/user-pictures/100/male3-512.png",
"text" : "Hello, I'm Ed, your personal assistant cum friend",
"timeStamp" : "1476880306"
}
}
}


}

This is my node.js code:

ref.on("child_changed", function(snapshot){
snapshot.ref.child("messages").on("child_added", function(itemSnapshot) {
var mytemp = itemSnapshot.child("text");
console.log(mytemp);
});
});






NOTE I viewed some similar questions on stackoverflow but when I implemented them, I came to know that they belonged to the outdated version of the firebase and didn't work in this current version.


EDIT By using the following code, I'm now getting
null
for each child added. Also, I want to ask how to get the parent's or user's id whose child has changed.
The code is:

ref.on("child_changed", function(snapshot){
//using limitToLast(1) to get last value only
snapshot.ref.child("messages").orderByKey().limitToLast(1).once("value", function(itemSnapshot) {
var mytemp = itemSnapshot.child("text").val();
console.log(mytemp);


});
});

console.png This is the screenshot of console after using this code
I got my answer for the aove question, but only remaining doubt is how to get the parent of the node whose child has changed?

Please feel free to ask for any more clarification if and when needed

Thanks!!

Answer

I think you may be looking for this:

ref.on("child_changed", function(snapshot){
    snapshot.child("messages").forEach(function(itemSnapshot) {
        var mytemp = itemSnapshot.child("text").val();
        console.log(mytemp);
    });
});