rahul singhania rahul singhania - 24 days ago 4
Node.js Question

node.js- How to get the parent of the node whose child has changed and grand child has added?

This is my json file:

{
"ERyWg81WxrXUb0sjsu9hv9T7K0E3" : {
"intents" : {
"intentName" : "",
"intentValue" : ""
},
"messages" : {
"-KViVgc7ZG051eMXP0-5" : {
"name" : "Ed",
"text" : "Hello, I'm Ed, your personal assistant cum friend",
"timestamp" : "1476880306"
}
}
},
"Y9UNlizDSobddO8cdq7K4ChipYa2" : {
"intents" : {
"intentName" : "",
"intentValue" : ""
},
"messages" : {
"-KViVgc7ZG051eMXP0-5" : {
"name" : "Ed",
"text" : "Hello, I'm Ed, your personal assistant cum friend",
"timestamp" : "1476880306"
}
}
}
}


Here,
ERyWg81WxrXUb0sjsu9hv9T7K0E3
and
Y9UNlizDSobddO8cdq7K4ChipYa2
are user Ids and they have two children namely,
intents
and
messages
who further have their children as shown in the JSON structure above.

Now, when a user sends a message, the message is added to the
messages
child of the user. Also ,it must be noted that other users can also be added or removed from the database.

Therefore, when a message is added, how to know the id of the user whose has messaged. For eg: I should get
ERyWg81WxrXUb0sjsu9hv9T7K0E3
when
ERyWg81WxrXUb0sjsu9hv9T7K0E3
user messages and a message is added to the
messages
subdirectory of
ERyWg81WxrXUb0sjsu9hv9T7K0E3
. I have to do this using firebase node.js sdk on server side.

For reference, my node.js server side code for getting new messages is:

var db = firebase.database();
var ref = db.ref("/");
console.log("Listening ...\n");
var text, name, timeStamp;
var newPost = {};
ref.on("child_changed", function(snapshot){
snapshot.child("messages").forEach(function(itemSnapshot) {
text = itemSnapshot.child("text").val();
name = itemSnapshot.child("name").val();
timeStamp = itemSnapshot.child("timeStamp").val();
});

Answer

There's no fundamental difference between using the admin (a.k.a. server) SDK and the client SDKs. The event listeners behave exactly the same.

You will not get the information you are looking for from the child event listeners, neither about the parent, nor which descendant triggered the change.

You need to change your database schema and/or your subscription strategy to facilitate your goals. At the very least, you should:

  1. Have a single (not per-user) node for all outgoing messages the server can simply observe. A child_added event will mean a message getting sent.
  2. Include the sender, recipient information in the message itself.
    You can use security rules to make sure that the client cannot falsify the sender's identity. With some creativity, you can also ensure that a user may only send another messages if he has permission to do do.